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.
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))
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'
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.