python - 驳回一次

标签 python algorithm

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

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/

相关文章:

algorithm - 数字异或 = X

algorithm - 这个算法的空间复杂度是多少?

Python 双向映射

c - 如何设计一个不使用这么多内存的哈希表?

algorithm - 通路/道路铺设问题

python - 在python中将正(+)和负(-)号更改为整数

algorithm - 估算 Google App Engine 查询中的结果数

python - 从xml数据中获取第二个标签值

python - django-tables2 中带有 render_* 方法的列不起作用

python - 通过管道将 Haskell 程序连接到 Python 程序(在 Python 中)