如何删除字符串中某个单词的实例和可能的多个实例并返回字符串(CODEWARS dubstep)

2024-06-16 10:55:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过使用python进行CODEWARS dubstep挑战

我的代码如下,它工作正常,我通过了kata测试。然而,这花了我很长时间,我最终使用了暴力手段(新手)

(基本上更换和剥离管柱,直到其工作)

对如何改进我的代码有什么意见吗

任务摘要:

Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.

For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".

song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
# => WE ARE THE CHAMPIONS MY FRIEND

song_decoder("AWUBBWUBC"), "A B C","WUB should be replaced by 1 space"
song_decoder("AWUBWUBWUBBWUBWUBWUBC"), "A B C","multiples WUB should be replaced by only 1 space"
song_decoder("WUBAWUBBWUBCWUB"), "A B C","heading or trailing spaces should be removed"


提前感谢,(我也是stackoverflow的新手)

我的代码:

def song_decoder(song):
new_song = song.replace("WUB", " ")
new_song2 = new_song.strip()
new_song3 = new_song2.replace("   ", "  ")
new_song4 = new_song3.replace("  ", " ")
return(new_song4)

Tags: andofthe代码numbernewsongbe
1条回答
网友
1楼 · 发布于 2024-06-16 10:55:01

我不知道它是否能改善它,但我会使用splitjoin

text = 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'
text = text.replace("WUB", " ")
print(text)
words = text.split()
print(words)
text = " ".join(words)
print(text)

结果

 WE ARE  THE CHAMPIONS MY FRIEND 
['WE', 'ARE', 'THE', 'CHAMPIONS', 'MY', 'FRIEND']
WE ARE THE CHAMPIONS MY FRIEND

编辑:

抖动不同的版本。我分割usinsgWUB,但是它会在两个WUB之间创建空元素,需要删除它们

text = 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'

words = text.split("WUB")
print(words)

words = [x for x in words if x]    # remove empty elements
#words = list(filter(None, words))  # remove empty elements
print(words)

text = " ".join(words)
print(text)

相关问题 更多 >