作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我的代码旨在遍历拆分为列表的字符串,并用新的字符串替换每个旧的字符串,然后返回该字符串。但是我的问题是,只有第一次出现被计算在内,其他的似乎保持不变:
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/
编写一个测试来测试我的应用程序的删除功能。我创建了一个模拟删除 $modal 来模拟取消/确认删除。 var modalInstanceMock= { result:
我是一名优秀的程序员,十分优秀!