如何将主要包含数字的字符串拆分为列表?我试过str.split()
了,但由于每个数字都用逗号分隔,我无法将字符串转换为整数列表。例如:
a='text,2, 3, 4, 5, 6'
当我这样做split
时
b=['text,2,', '3,', '4,', '5,', '6']
有没有办法将整数隔离到一个列表中?
使用regex
:
>>> a = 'text,2, 3, 4, 5, 6'
>>> import re
>>> re.findall(r'\d+', a)
['2', '3', '4', '5', '6']
str.isdigit
使用和列表理解的非正则表达式解决方案:
>>> [y for y in (x.strip() for x in a.split(',')) if y.isdigit()]
['2', '3', '4', '5', '6']
如果您希望将字符串转换为整数,则只需调用int()
列表中的项目。
>>> import re
>>> [int(m.group()) for m in re.finditer(r'\d+', a)]
[2, 3, 4, 5, 6]
>>> [int(y) for y in (x.strip() for x in a.split(',')) if y.isdigit()]
[2, 3, 4, 5, 6]
Here is a solution that doesn't use Regex:
>>> a='text,2, 3, 4, 5, 6'
>>> # You could also do "[x for x in (y.strip() for y in a.split(',')) if x.isdigit()]"
>>> # I like this one though because it is shorter
>>> [x for x in map(str.strip, a.split(',')) if x.isdigit()]
['2', '3', '4', '5', '6']
>>> [int(x) for x in map(str.strip, a.split(',')) if x.isdigit()]
[2, 3, 4, 5, 6]
>>>