我对编程很陌生(这是我第一次在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'
的错误。任何帮助或指出我的正确方向将不胜感激。在
在一行中完成这两个步骤。在
结果
^{2}$字符串在Python中是不可变的。所以改变一个字符串(就像你试图用“replace”函数做的那样)并不会改变你的变量“song”。相反,它创建了一个新的字符串,您可以通过不将其分配给某个对象而立即将其丢弃。你可以的
或者,为了缩短它(也可以称之为可读性较差),您可以
^{2}$你很接近了!^{} 不能“就地”工作;它返回一个新字符串,该字符串已对其执行了请求的替换。在
请执行以下操作:
例如:
^{2}$相关问题 更多 >
编程相关推荐