adep7 adep7 - 3 months ago 11x
Python Question

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:

would give the output:
. 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 'A B 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'