我的代码旨在遍历拆分为列表的字符串,并用新的字符串替换每个旧的字符串,然后返回该字符串。 但是我的问题是,只有第一次出现被计算在内,其他的似乎保持不变:
def replace(s, old, new):
ch=""
i=0
newMsg=s.split()
print newMsg
for ch in newMsg:
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
else:
i = i +1
return ' '.join(newMsg)
最佳答案
好吧,因为如果你的 ch 确实等于 old,i 就不会增加。可以这样修复。
def replace(s, old, new):
ch=""
i=0
newMsg=s.split()
print newMsg
for ch in newMsg:
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
i=i+1
else:
i = i +1
return ' '.join(newMsg)
也就是说,您不需要那样做。您可以使用枚举。
def replace(s, old, new):
ch=""
newMsg=s.split()
print newMsg
for i,ch in enumerate(newMsg):
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
return ' '.join(newMsg)
关于python - 驳回一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47895556/