Reputation: 55
My code is meant to iterate through a string that is split into a list and replace every old occurrence with the new one then return the string. However my problem is that only the first occurrence is counted and the others seems to be kept the same:
def replace(s, old, new):
ch=""
i=0
newMsg=s.split()
print newMsg
for ch in newMsg:
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
else:
i = i +1
return ' '.join(newMsg)
Upvotes: 0
Views: 51
Reputation: 3064
Well because if your ch does equal old, i isn't increased. Could fix like this.
def replace(s, old, new):
ch=""
i=0
newMsg=s.split()
print newMsg
for ch in newMsg:
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
i=i+1
else:
i = i +1
return ' '.join(newMsg)
That being said, you don't need to do it like that. You can use enumerate.
def replace(s, old, new):
ch=""
newMsg=s.split()
print newMsg
for i,ch in enumerate(newMsg):
if ch==old:
newMsg[i]=newMsg[i].replace(old, new)
return ' '.join(newMsg)
Upvotes: 2