Python新手自制字符串替换函数异常:输入shyer未输出预期结果
字符串替换函数死循环问题排查与修复
问题原因
你的First_Replace函数最后一段的while循环存在死循环问题:
当输入"shyer"时,匹配位置s=1,len(part)=2,所以循环初始i=1+2=3。进入循环后,代码只执行new_word += word[i],但没有对i进行递增操作,导致i始终等于3,循环条件i < len(word)(此时len(word)=5,3<5永远成立),程序陷入死循环,无法继续执行到输出步骤。
修复后的代码
只需要在while循环内添加i += 1即可解决:
word = input("Enter a string : ") def Ino_String(word,part): # if part is in word s will indicate the position where the starting position of part is in word # if not s will stay -1 s = -1 i = 0 j = 0 count = 0 while i < len(word): if word[i] == part[j]: count += 1 j += 1 i += 1 else: count = 0 i = i - j + 1 j = 0 if count == len(part): s = i - len(part) break return s def First_Replace(word, part, new_part): s = Ino_String(word, part) if s != -1 : new_word = "" for i in range(s): new_word += word[i] for i in range(0, len(new_part)): new_word += new_part[i] i = s + len(part) while i < len(word): new_word += word[i] i += 1 # 添加这一行,让循环变量递增 else: new_word = "Error: the part you want to replace is not in the string" return new_word print(str(Ino_String(word,"hy"))) new_word = First_Replace(word, 'hy', "how") print(new_word)
测试验证
输入"shyer"时,现在会正常输出1和shower,符合预期。
内容的提问来源于stack exchange,提问作者Moha Med
相关产品推荐
相关产品推荐

