1

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...!

4 Answers 4

3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Using string as variable name is also a bad idea :-)
there is an in-built python module name string. So definitely a bad idea. Try import string
3

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:

1 Comment

the advantage to this over regex is that it will work with any type of number eg. 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
0
  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

0
string = "groups(1,12,23,12)".replace('groups(','').replace(')','')
outputList = [int(x) for x in string.split(',')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.