【发布时间】:2021-05-24 22:54:42
【问题描述】:
我试图返回一个用新字符替换给定旧字符的语句,但循环在第一次迭代后继续退出。
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
我知道在 python 中已经定义了替换函数,但这是我被告知这样做的方式。 (与for ch in s 位相同)
【问题讨论】:
-
return newstring不应该在迭代中。删除一个缩进级别。 -
立即中断的
while循环与if语句相同。 -
所以这两个
while循环应该是if和else。
标签: python loops replace iteration