3

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?

7
  • It seems like you intended range(len(s1)) instead of range(s1). Commented Feb 15, 2014 at 5:37
  • I can't use any python methods. I basically have to build it from scratch. Commented Feb 15, 2014 at 5:39
  • Is this because you are doing an assignment? Otherwise there is no reason not to use python methods. Commented Feb 15, 2014 at 5:39
  • 1
    @cobra range is a python method :) Commented Feb 15, 2014 at 5:39
  • Actually, technically the [] operator is a method, since to use it it calls the __getitem__ or __getslice__ methods internally. Commented Feb 15, 2014 at 5:42

1 Answer 1

5
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)
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, can't use any python methods.
i changed the code, but it only replaces the first 'I' with 'a' and ignores the second 'I'.
@cobra Please edit the question and update with the changed code.
Thanks a lot for your input. It helped a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.