首页 > 解决方案 > findall() 返回一个列表,但它不添加列表中的元素

问题描述

import re
nos="to do with your newfound skills.  338  3803"
for x in nos:
    y=re.findall("[0-9]+",nos)
print("total is :",sum(y))

尽管变量 y 返回一个列表,但仍然必须明确提及 y=list() ,它也会给出此错误:

“TypeError:+ 的不支持的操作数类型:'int' 和 'str'”

标签: pythonregex

解决方案


您已经有答案解释了为什么它在评论部分不起作用,但在这种情况下请考虑列表理解,

nos="to do with your newfound skills.  338  3803"
print(sum([int(s) for s in nos.split() if s.isdigit()]))
>>>>4141

甚至更好,正如@EdwardMinnix 所说

print(sum(int(s) for s in nos.split() if s.isdigit()))

推荐阅读