1

I am trying to replace a character in a string using python. I am using a function called find_chr to find the location of the character that needs to be replaced.

def main():
    s='IS GOING GO'
    x='N'
    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_chr(s1,s2,s3):
    return print(s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):])


main()

My problem is that instead of getting the new string, the function is returning 'False'. I would appreciate any pointer to get the replaced string.

2
  • Looks like you changed print(rep_chr(s,x,y)) to (rep_chr(s,x,y))... Commented Feb 15, 2014 at 4:33
  • 1
    Why are you not using str.replace? Just trying to recreate it for fun? Commented Feb 15, 2014 at 5:07

3 Answers 3

2

change

return print(s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):])

to

return s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):]

and print the result in your main:

print(rep_chr(s,x,y))
Sign up to request clarification or add additional context in comments.

Comments

2

There is an inbuilt function:

string.replace(old, new, count)

this returns a modified copy

count is optional and is the number of times to replace - if it is set to 2 it will replace the first two occurrences.

string = 'abc abc abc def'
string.replace('abc','xyz',2)

returns

'xyz xyz abc def'

Comments

1

The problem is in your print statement inside rep_chr function.

s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):]

The above statement means is s1 equal to s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):]? which is false and that's why you are getting False as output.

Comments

Your Answer

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