如何按顺序向行中添加列表内字符串?TypeError报错解决
问题分析与解决方案
错误原因
- 变量定义缺失:第一行代码未给列表指定变量名,正确写法应为
a = ["one","two","three"] - 循环取值逻辑错误:
for i in a中,i本身就是列表里的每个字符串元素(如"one"、"two"),此时用a[i]会触发报错,因为列表索引仅支持整数或切片,不能用字符串作为索引。 - 输出格式不符:原代码的输出字符串缺少空格和结尾句号,导致无法匹配预期格式。
修正后的代码
a = ["one","two","three"] for i in a: print("it starts with: " + i + " or more.")
输出结果
it starts with: one or more. it starts with: two or more. it starts with: three or more.
也可以用更简洁的f-string写法:
a = ["one","two","three"] for item in a: print(f"it starts with: {item} or more.")
内容的提问来源于stack exchange,提问作者Ghost31
相关产品推荐
相关产品推荐

