Home > Net >  python replace() function is not working as supposed
python replace() function is not working as supposed

Time:08-28

res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
    res.replace(i,j)
print(res)

the output expected is: hello what I got instead is heeellooo

any idea why this is happening??

CodePudding user response:

Classical problem:

res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
    res=res.replace(i,j)
print(res)

CodePudding user response:

In the for loop you have to mention that certain content of variable "res" needs to be replaced with certain content from the variable "D".

So, you have to change that line of code to this:

res = res.replace(i,j)

CodePudding user response:

res = "heeellooo"
D = {"aaa":"a","eee":"e","iii":"i","ooo":"o","uuu":"u","yyy":"y"}
for i,j in D.items():
    res = res.replace(i,j) # use the returned value of `replace()`
print(res)
  • Related