Reputation: 11
I'm trying to return a statement that replaces given old characters with new characters, but the loop keeps exiting after the first iteration.
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
while (ch == old_ch):
newstring += new_ch
break
while (ch != old_ch):
newstring += ch
break
return newstring
I know that there are already defined replace functions in python, but this is the way I've been told to do it. (same with the for ch in s
bits)
Upvotes: 1
Views: 1319
Reputation: 906
Try this, so that you will get a better understanding of the iteration.
def test(s, old_ch, new_ch):
newstring = ""
for ch in s:
print(f"ch is {ch}")
if (ch == old_ch):
print(f"if condition is True for ch {ch} and old_ch {old_ch}")
newstring += new_ch
else:
print(f"elif condition is True for ch {ch} and old_ch {old_ch}")
newstring += ch
print(newstring)
return newstring
call this function
test("New to Python", "t", "y")
Output is
ch is N
elif condition is True for ch N and old_ch t
ch is e
elif condition is True for ch e and old_ch t
ch is w
elif condition is True for ch w and old_ch t
ch is
elif condition is True for ch and old_ch t
ch is t
if condition is True for ch t and old_ch t
ch is o
elif condition is True for ch o and old_ch t
ch is
elif condition is True for ch and old_ch t
ch is P
elif condition is True for ch P and old_ch t
ch is y
elif condition is True for ch y and old_ch t
ch is t
if condition is True for ch t and old_ch t
ch is h
elif condition is True for ch h and old_ch t
ch is o
elif condition is True for ch o and old_ch t
ch is n
elif condition is True for ch n and old_ch t
Upvotes: 0
Reputation: 3
for ch in s
statement is used to loop over every character of the string.
Hence the while loop inside the for loop is not required.
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if(ch == old_ch):
newstring = newstring+new_ch
if(ch != old_ch):
newstring = newstring + ch
return newstring
This code does the intended work you want to achieve.
Upvotes: 0
Reputation: 2054
There are two things you need to change.
Instead of using a while-loop and breaking, just use an if-statement. Your code will still work the same way, but it'll be much more readable.
Move the return statement outside of the for-loop, i.e. unindent it. This way newstring
won't be returned until the entire for-loop has been executed, which is the desired behavior.
The full corrected code is below:
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if (ch == old_ch):
newstring += new_ch
else:
newstring += ch
return newstring
print(test("Megalovania", "a", "o"))
# Prints Megolovonio
Upvotes: 1