Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all instances of a character in a string using python

trying to replace all instances of a given character in a string with a new character. The following is my code:

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()

Edited the code, but it is still replacing the first 'I' with 'a' and ignoring the second 'I'. Any suggestion?


1 Answers

for i in range(s1):

Here s1 is a string and you are passing it to range function, which expects only numbers as parameters. That is the problem. You should be using the length of the string instead

for i in range(len(s1)):

But, your actual problem can be solved with str.replace, like this

s='IS GOING GO'
x='I'
y='a'
print(s.replace(x, y))

If you want to solve without str.replace, you can do it like this

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

Output

aS GOaNG GO

The same program can be written like this as well

s, result, x, y ='IS GOING GO', "", "I", "a"
for char in s:
    result += y if char == x else char
print(result)
like image 112
thefourtheye Avatar answered May 26 '26 08:05

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!