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

遍历含特殊字符的字符串列表触发TypeError的解决方法及原因

问题:遍历列表生成正则替换代码时触发TypeError错误

原代码

colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']

symbolic_numbers = ['23', '22', '21', '20', '3', '2', '1']

body = ''
for n in coloquial_numbers:
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
    #body += """    input_text = re.sub(r'""" + coloquial_numbers[n] + """', '""" + symbolic_numbers[n] + """', input_text)\n"""

print(repr(body))

报错信息

Traceback (most recent call last):
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
TypeError: list indices must be integers or slices, not str

预期输出

input_text = re.sub(r"veinti[\s|-|]*tres", "23", input_text)
    input_text = re.sub(r"veinti[\s|-|]*dos", "22", input_text)
    input_text = re.sub(r"veinti[\s|-|]*uno", "21", input_text)
    input_text = re.sub("tres", "3", input_text)
    input_text = re.sub("dos", "2", input_text)
    input_text = re.sub("uno", "1", input_text)

错误原因

你遍历colloquial_numbers时,变量n拿到的是列表中的字符串元素(比如第一次循环n是'veinti[\\s|-|]tres'),但列表的索引只能是整数或切片,用字符串当索引必然触发TypeError。这个问题和字符串里的特殊字符完全无关——哪怕你用普通字符串列表这么写,同样会报错。

修复方法

有两种简洁的修复方式:

方法1:用enumerate遍历索引和元素

通过enumerate同时获取元素的索引和值,再用索引取对应列表的元素:

colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']
symbolic_numbers = ['23', '22', '21', '20', '3', '2', '1']

body = ''
for idx, colloquial in enumerate(colloquial_numbers):
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(colloquial, symbolic_numbers[idx])

print(repr(body))

方法2:用zip配对两个列表遍历

zip会把两个列表中对应位置的元素配对,直接遍历配对后的元组即可:

colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']
symbolic_numbers = ['23', '22', '21', '20', '3', '2', '1']

body = ''
for colloquial, symbolic in zip(colloquial_numbers, symbolic_numbers):
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(colloquial, symbolic)

print(repr(body))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:51:17