简体   繁体   中英

Python: Remove words from a given string

I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: ABC . From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:

def song_decoder(song):
     song.replace("WUB", " ")
     return " ".join(song.split())

I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'AB C' after running the code. Any help or pointing me in the right direction would be appreciated.

You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Do this instead:

def song_decoder(song):
     song = song.replace("WUB", " ")
     return " ".join(song.split())

For example:

In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'

Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do

def song_decoder(song):
    result = song.replace("WUB", " ")  # replace "WUB" with " "
    result = result.split()            # split string at whitespaces producing a list
    result = " ".join(result)          # create string by concatenating list elements around " "s
    return result

or, to make it shorter (one could also call it less readable) you can

def song_decoder(song):
    return " ".join(song.replace("WUB", " ").split())

Do the both steps in a single line.

def song_decoder(song):
    return ' '.join(song.replace('WUB',' ').split())

Result

In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'

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