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]
import stringFor 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:
1e4, 1.99, 0x9 etc. and it will even work for any other type string, dict, etc I think this is the best approach, the general rule is to always avoid regex where possible as well