简体   繁体   中英

Python: String manipulation function error, returns "None"

I am currently having issues with string manipulation in Python. I am trying to create a function (called nameManipulate) where it finds the beginning of each word in the string and replaces it with "n" to work with later on in the program. I have no idea if there is a faster or more efficient method of doing this but here is mine (the random song is selected from an SQL database):

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)

The result prints the full data received by the database as expected, but it should also print the manipulated string, instead it simply prints "None".

37 Smells Like Teen Spirit Nirvana
None

Instead of "nmells Like Teen npirit", it should have printed "nmells nike neen npirit"

Any advice or help would be greatly appreciated, I would love to learn exactly what's gone wrong and how to fix it. Appreciated!

The function needed to be edited, the new_title needed to be manipulated rather than 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

This is a perfect case for using regular expressions.

If you don't know about regular expressions, it is an amazing tool to master. See the official documentation .

Here is some code:

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']

The method re.sub() receives a string describing a regular expression that you want to find (in our case, the string ' \\w' represents a whitespace followed by any character). Then we ask to replace by ' n' , that is, a whitespace followed by n. Then we pass the string we want to replace, which is each name in the names list.

You can do much much more with regular expressions so it is worth having a detailed look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM