You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序无限循环问题求助:元音后添加"bi"功能异常

问题根源

你的代码触发无限循环的关键问题:

  • 遍历+修改原列表冲突:for i in NameList循环时,每次插入"bi"都会拉长列表,循环会不断遍历新添加的元素,永远无法结束。
  • index()方法的错误使用:NameList.index(i)只会返回第一个匹配字符的索引,比如"aya"里的第二个a会被错误定位到第一个a的位置,导致重复在该位置插入"bi",彻底陷入死循环。
修复后的代码

直接创建新列表构建结果,避开原列表修改带来的遍历问题,逻辑更直观:

"""Welcome to the code of BoBi Sprache. This Sprache aka Language will 
put the letter "bi" after each vowel letter in your name"""

print("Welcome to the BoBiSprache programm")
name = input("Please enter your name to be BoBied :D : ").lower()
vowels = {"a", "e", "i", "o", "u"}  # 集合查询效率更高

def bobify_name(name_str):
    result_chars = []
    for char in name_str:
        result_chars.append(char)
        if char in vowels:
            result_chars.append("bi")
    return ''.join(result_chars).title()

new_name = bobify_name(name)
print(f"Your New Name is: {new_name}")
效果验证

输入"aya"时,输出为Abiyabi,完全符合预期,且不会出现无限循环。

内容的提问来源于stack exchange,提问作者Mohammed Sabaawi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:01:33