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

如何将逗号分隔的数字字符串转为列表?解决TypeError报错

问题解决:TypeError: 'str' object cannot be interpreted as an integer

错误原因

你调用split(",", " ")时犯了参数错误:str.split()的第二个参数是最大分割次数,必须传入整数,而你传了字符串" ",这就触发了类型错误。

正确解决方法

方法1:先按逗号分割,再清理每个元素的空格

先通过逗号分割字符串,再用strip()去除每个元素前后的空格,还可以直接转成整数类型:

numbers = "1, 2, 3, 4, 5, 500, 600, 800"
# 得到字符串列表
str_list = [num.strip() for num in numbers.split(",")]
# 转成整数列表(如果需要)
int_list = [int(num.strip()) for num in numbers.split(",")]

print(str_list)  # 输出: ['1', '2', '3', '4', '5', '500', '600', '800']
print(int_list)  # 输出: [1, 2, 3, 4, 5, 500, 600, 800]

方法2:用正则表达式匹配分割模式

如果字符串里的空格数量不固定(比如有的是多个空格),可以用正则表达式匹配逗号+任意数量空格的模式来分割:

import re

numbers = "1, 2, 3, 4, 5, 500, 600, 800"
# 字符串列表
str_list = re.split(r",\s*", numbers)
# 整数列表
int_list = [int(num) for num in re.split(r",\s*", numbers)]

print(str_list)  # 输出: ['1', '2', '3', '4', '5', '500', '600', '800']
print(int_list)  # 输出: [1, 2, 3, 4, 5, 500, 600, 800]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:05:24