Jothimani Jothimani - 5 months ago 15
Python Question

Python:- Convert a string into list

I have a string like

groups(1,12,23,12)
and I want to convert it into a list like
[1,12, 23, 12]
.

I tried this code, but output is not as excepted.

str = 'groups(1,12,23,12)'
lst = [x for x in str]


Please let me know...!

Answer
  1. Use regular expression to find numbers from the input string.
  2. Use map method to convert string to integer.

e.g.

>>> import re
>>> a = 'groups(1,12,23,12)'
>>> re.findall("\d+", a)
['1', '12', '23', '12']
>>> map(int, re.findall("\d+", a))
[1, 12, 23, 12]
Comments