Reputation: 109
So I have this function below where I want to return a new string where every ch is replaced with ch2:
def replace(s, ch, ch2):
'''(str, str, str) - > str
Return a new string where every instance of ch in s is replaced with ch2
Precondition: len(ch) == 1 and len(ch2) == 1
'''
i = 0
m = s[i]
while i < len(s):
if s[i] == ch:
return ch2
m = m + s[i]
i += 1
return m
When I type this:
replace('razzmatazz', 'z', 'r')
I want the output to be this:
'rarrmatarr'
I tried several ways, but I'm only getting 'r' or 'rr'
.
Can someone tell me where I went wrong?
Upvotes: 0
Views: 3803
Reputation: 3307
I think your code should be.,
i = 0
m = s[i]
while i < len(s):
if s[i] == ch:
m = m + ch2 // Here you are lagging.
else
m = m + s[i]
i += 1
return m
Because , In your code, when in the string razzmatazz
if first z
is matched then instead of replacing.,
it returns the ch2
i.e r
. Hence you are getting r
.
Upvotes: 1
Reputation: 707
Your're returning ch2
from the function as soon as you find ch
in your original string, so that can't work in the way you expect it to do. You have to add the correct character to a new string, and then return that string after you iterate over every character in the original string.
i = 0
m = ''
while i < len(s):
m += ch2 if s[i] == ch else s[i]
i += 1
return m
Also, as pointed in the other answers, there are better ways to accomplish this.
Upvotes: 2
Reputation: 27028
This is built in to the language
'razzmatazz'.replace('z', 'r')
'rarrmatarr'
If I would use your style I would write something more along the lines of:
def replace(s, ch, ch2):
s2 = list(s)
i=0
while i < len(s):
if s2[i] == ch:
s2[i]=ch2
i=i+1
return "".join(s2)
Upvotes: 0
Reputation: 298176
return
immediately returns a value and exits the function, even if it's in a loop. You probably want to get rid of that while
loop and use a nice for
loop instead:
def replace(s, ch, ch2):
'''(str, str, str) - > str
Return a new string where every instance of ch in s is replaced with ch2
Precondition: len(ch) == 1 and len(ch2) == 1
'''
result = ''
for char in s:
if char == ch:
result += ch2
else:
result += char
return result
Although it'd be better if you just used the built-in str.replace
method:
def replace(s, ch, ch2):
return s.replace(ch, ch2)
Or more concisely:
replace = str.replace
Upvotes: 0
Reputation: 582
Why don't you use str.replace(), available in Python?
>>> s = 'razzmatazz'
>>> s.replace('z', 'r')
'rarrmatarr'
No need to create a custom function to get done what you want
Upvotes: 0