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

如何解决Python中的substring not found错误?Replit代码问题求助

问题分析与解决

你的错误出在info[item.index(i)] = item这行:

  • item是用户输入的答案(比如名字、生日),i是问题文本(比如"What is your name? ")
  • str.index(sub)方法是用来在字符串里查找子串sub的位置,你现在是拿答案去搜问题文本,显然答案里不可能包含问题,所以抛出ValueError: substring not found。

你真正要做的是:把每个问题对应的用户答案,存入字典info中对应的键(也就是items列表里的元素)。因为questions和items是一一对应的,有两种简单的实现方式:

方法1:用enumerate获取索引

info = {"name":"", "date of birth": "", "telephone number": "", "email": "", "address": ""}
questions = ["What is your name? ", "When were you born? ", "What is your telephone number? ", "What is your email? ", "What is your address? (Don't say it if you don't want to) "]
items = ["name", "date of birth", "telephone number", "email", "address"]

# 用enumerate同时拿到问题的索引和文本
for idx, q in enumerate(questions):
    answer = input(q)
    # 通过索引取对应的字典键,赋值用户输入的答案
    info[items[idx]] = answer

# 测试输出
print(info)

方法2:用zip配对问题和键

这种方式更直观,直接把questions和items里的对应元素配对遍历:

info = {"name":"", "date of birth": "", "telephone number": "", "email": "", "address": ""}
questions = ["What is your name? ", "When were you born? ", "What is your telephone number? ", "What is your email? ", "What is your address? (Don't say it if you don't want to) "]
items = ["name", "date of birth", "telephone number", "email", "address"]

# zip将两个列表的对应元素配对,遍历每一组(问题,键)
for q, key in zip(questions, items):
    answer = input(q)
    info[key] = answer

# 测试输出
print(info)

两种方法都能实现你的需求,推荐方法2,逻辑更清晰,不需要处理索引。

内容的提问来源于stack exchange,提问作者Python User

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:50:29