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...!
You could use re.findall
method.
And don't use str
as variable name.
>>> import re
>>> s = 'groups(1,12,23,12)'
>>> re.findall(r'\d+', string)
['1', '12', '23', '12']
>>> [int(i) for i in re.findall(r'\d+', s)]
[1, 12, 23, 12]
Without regex,
>>> s = 'groups(1,12,23,12)'
>>> [int(i) for i in s.split('(')[1].split(')')[0].split(',')]
[1, 12, 23, 12]
For an approach without regex
>>> a = "groups(1,12,23,12)"
>>> a= a.replace('groups','')
>>> import ast
>>> list(ast.literal_eval(a))
[1, 12, 23, 12]
Ref:
eg
>>> 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]
string = "groups(1,12,23,12)".replace('groups(','').replace(')','')
outputList = [int(x) for x in string.split(',')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.