Python:从给定的字符串中删除单词

2024-06-16 10:53:05 发布

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

我对编程很陌生(这是我第一次在stackoverflow上发表文章),但是我发现这个问题相当困难。在本例中,我应该删除给定的字符串(WUB),并用空格替换它。例如:song_decoder(WUBWUBAWUBWUBWUBBWUBC)将给出输出:A B C。从这个论坛上的其他问题中,我可以确定我需要替换“WUB”并使用split/join删除空白。这是我的代码:

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

我不确定我在哪里出错,因为我在运行代码后出现了WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C'的错误。任何帮助或指出我的正确方向将不胜感激。在


Tags: 字符串代码song编程stackoverflowsplit空格join
3条回答

在一行中完成这两个步骤。在

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

结果

^{2}$

字符串在Python中是不可变的。所以改变一个字符串(就像你试图用“replace”函数做的那样)并不会改变你的变量“song”。相反,它创建了一个新的字符串,您可以通过不将其分配给某个对象而立即将其丢弃。你可以的

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

或者,为了缩短它(也可以称之为可读性较差),您可以

^{2}$

你很接近了!^{}不能“就地”工作;它返回一个新字符串,该字符串已对其执行了请求的替换。在

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.

请执行以下操作:

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

例如:

^{2}$

相关问题 更多 >