解雇一次

问题描述 投票:0回答:1

我的代码用于迭代一个字符串,该字符串被拆分为一个列表,并用新的一个替换每个旧的出现,然后返回该字符串。但是我的问题是只计算第一次出现,其他看起来保持不变:

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)
python algorithm
1个回答
2
投票

好吧,因为如果你的ch确实相同,我不会增加。可以这样解决。

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)
© www.soinside.com 2019 - 2024. All rights reserved.