所以我在下面有这个函数,我想返回一个新字符串,其中每个 ch 都替换为 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
当我输入这个:
replace('razzmatazz', 'z', 'r')
我希望输出是这样的:
'rarrmatarr'
我尝试了几种方法,但我只得到'r' or 'rr'
.
有人能告诉我哪里出错了吗?