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

如何用Python将字符串转换为整数列表?

解决方法

你的问题出在直接遍历字符串的每个字符,逗号和空格这些非数字字符自然没法转成整数。正确的步骤应该是先把字符串按分隔符拆分,再处理每个ID:

方法一:列表推导式(简洁写法)

stringIds = "948274432, 948364892, 943224012"
intList = [int(id.strip()) for id in stringIds.split(',')]

方法二:分步循环(更直观)

stringIds = "948274432, 948364892, 943224012"
intList = []
# 先按逗号拆分字符串,得到每个带空格的ID字符串
id_strings = stringIds.split(',')
for id_str in id_strings:
    # 去掉前后空格,再转成整数
    int_id = int(id_str.strip())
    intList.append(int_id)

两种方法最终都会得到你想要的结果:

intList = [948274432, 948364892, 943224012]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:05:20