Python:字符串操作函数错误,返回“ None”

问题描述 投票:0回答:2

我目前在使用Python进行字符串操作时遇到问题。我正在尝试创建一个函数(称为nameManipulate),在该函数中找到字符串中每个单词的开头,并将其替换为“ n”,以便稍后在程序中使用。我不知道是否有更快或更有效的方法来做到这一点,但这是我的(从SQL数据库中选择随机歌曲):

import sqlite3, random

db = sqlite3.connect('songsdb')
cursor = db.cursor()

number = str(random.randint(1,50))

cursor.execute('''
SELECT songid,title,artist FROM songs WHERE songid='''+number+'''
''')
all_rows = cursor.fetchall()
for row in all_rows:
    songid = row[0] # Integer
    title = row[1] # String (song name)
    artist = row[2] # String (song artist)
print(songid, title, artist)

def nameManipulate(title):
    new_title = title
    for letter in range(len(title)):
        if title[letter] == " ":
            new_title = title.replace(str(title[letter+1]), "n")
    new_title = new_title.replace(str(title[0]), "n")
    return new_title

displayTitle = str(nameManipulate(title))

print(displayTitle)

结果将按预期方式打印数据库接收到的全部数据,但是它也应该打印操作过的字符串,而只打印“ None”。

37 Smells Like Teen Spirit Nirvana
None

应该代替“ nmells nike neen npirit”打印“ nmells nike neen npirit”

任何建议或帮助都将不胜感激,我很想确切地了解出了什么问题以及如何解决。感激!

python string function
2个回答
0
投票

需要编辑功能,需要操纵new_title而不是title。

def nameManipulate(title):
    new_title = title
    for letter in range(len(title)):
        if title[letter] == " ":
            new_title = new_title.replace(str(title[letter+1]), "<letter>")
    new_title = new_title.replace(str(title[0]), "<letter>")
    return new_title

0
投票

这是使用正则表达式的完美案例。

如果您对正则表达式一无所知,那么它是掌握工具的绝佳工具。参见the official documentation

这里是一些代码:

import re

names = [
    '37 Smells Like Teen Spirit Nirvana',
    '38 Be My Baby',
]

replaces = [
    re.sub(r' \w', ' n', name) for name in names
]

print replaces
# ['37 nmells nike neen npirit nirvana', '38 ne ny naby']

方法re.sub()接收描述您要查找的正则表达式的字符串(在我们的示例中,字符串' \w'表示空格,后跟任何字符)。然后,我们要求替换为' n',即空格后跟n。然后,我们传递要替换的字符串,该字符串是name列表中的每个names

您可以使用正则表达式做更多的事情,因此值得详细了解。

© www.soinside.com 2019 - 2024. All rights reserved.