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

Python遍历字符串提取数字拼接时报列表索引类型错误如何解决

报错原因与问题分析

  • 直接报错来自你代码里的numbers[i]写法:你这里用到的i是遍历输入字符串得到的字符(类型为字符串,比如示例输入里的'1'/'a'/'w'/'4'),而列表的索引必须是整数,用字符串作为索引就会触发'list indices must be integers or slices, not str'报错。
  • 其余错误写法:
    1. int(i, numbers[i])不符合int函数的参数规则,int的第二个参数是进制参数,和你要实现的数字拼接需求完全无关。
    2. s.join(...)用法错误,join方法是用调用者作为分隔符,拼接括号内可迭代对象里的所有字符串元素,你要实现用+拼接提取到的数字,应该用'+'.join(numbers)。

修正后代码

def sum_of_digits(s):
  letters = []
  numbers = []

  for i in s:
    if i.isalpha():
     letters.append(i)
    elif i.isdigit():
      numbers.append(i)
  print("The extracted non-digits are: {} ". format(letters), end="\n")    
  print("The sum of digits operation performs", '+'.join(numbers))

sum_of_digits("1aw4") 

运行输出

The extracted non-digits are: ['a', 'w'] 
The sum of digits operation performs 1+4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:15:04