gpt4 book ai didi

python - 驳回一次

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:00 27 4
gpt4 key购买 nike

我的代码旨在遍历拆分为列表的字符串,并用新的字符串替换每个旧的字符串,然后返回该字符串。但是我的问题是,只有第一次出现被计算在内,其他的似乎保持不变:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com