使用python替换字符串中字符的所有实例

1 python string replace python-3.x

尝试用新字符替换字符串中给定字符的所有实例.以下是我的代码:

def main():
    s='IS GOING GO'
    x='I'
    y='a'

   rep_chr(s,x,y)


def find_chr(s,char):
    i=0
    for ch in s:
        if ch==char:
            return (i)
            break        
        i+=1
    return -1
def rep_ch(s,x,y):
    result=""

    for char in s:

        if char == x:
            print(result=result+ y )        
        else:
            return char   
main()
Run Code Online (Sandbox Code Playgroud)

编辑了代码,但它仍然用'a'替换第一个'I'而忽略了第二个'I'.有什么建议吗?

the*_*eye 5

for i in range(s1):
Run Code Online (Sandbox Code Playgroud)

s1是一个字符串,您将它传递给rangefunction,它只需要数字作为参数.那就是问题所在.您应该使用字符串的长度

for i in range(len(s1)):
Run Code Online (Sandbox Code Playgroud)

但是,你的实际问题可以str.replace像这样解决

s='IS GOING GO'
x='I'
y='a'
print(s.replace(x, y))
Run Code Online (Sandbox Code Playgroud)

如果你想在没有的情况下解决str.replace,你可以这样做

s, result, x, y ='IS GOING GO', "", "I", "a"
for char in s:
    if char == x:
        result += y
    else:
        result += char
print(result)
Run Code Online (Sandbox Code Playgroud)

产量

aS GOaNG GO
Run Code Online (Sandbox Code Playgroud)

同样的程序也可以这样写

s, result, x, y ='IS GOING GO', "", "I", "a"
for char in s:
    result += y if char == x else char
print(result)
Run Code Online (Sandbox Code Playgroud)