Reputation: 315
How do I split a string containing mostly numbers into a list? I tried str.split()
but since each number is separated by a comma I can't turn the string into a list of integers.
for example:
a='text,2, 3, 4, 5, 6'
when I do split
I get
b=['text,2,', '3,', '4,', '5,', '6']
Is there any way to isolate the integers into a list?
Upvotes: 0
Views: 234
Reputation: 250911
Use regex
:
>>> a = 'text,2, 3, 4, 5, 6'
>>> import re
>>> re.findall(r'\d+', a)
['2', '3', '4', '5', '6']
Non-regex solution using str.isdigit
and a List comprehension:
>>> [y for y in (x.strip() for x in a.split(',')) if y.isdigit()]
['2', '3', '4', '5', '6']
If you want the string to be converted to integers then just call int()
on the items in the list.
>>> 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]
Upvotes: 3
Reputation:
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]
>>>
Upvotes: 2