【发布时间】:2015-04-14 11:49:54
【问题描述】:
我有一个像groups(1,12,23,12) 这样的字符串,我想把它转换成一个像[1,12, 23, 12] 这样的列表。
我试过这段代码,但输出并不例外。
str = 'groups(1,12,23,12)'
lst = [x for x in str]
请告诉我...!
【问题讨论】:
标签: python regex string list types
我有一个像groups(1,12,23,12) 这样的字符串,我想把它转换成一个像[1,12, 23, 12] 这样的列表。
我试过这段代码,但输出并不例外。
str = 'groups(1,12,23,12)'
lst = [x for x in str]
请告诉我...!
【问题讨论】:
标签: python regex string list types
您可以使用re.findall 方法。
并且不要使用str 作为变量名。
>>> 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]
没有正则表达式,
>>> s = 'groups(1,12,23,12)'
>>> [int(i) for i in s.split('(')[1].split(')')[0].split(',')]
[1, 12, 23, 12]
【讨论】:
import string
对于没有正则表达式的方法
>>> a = "groups(1,12,23,12)"
>>> a= a.replace('groups','')
>>> import ast
>>> list(ast.literal_eval(a))
[1, 12, 23, 12]
参考:
【讨论】:
1e4、1.99、0x9 等,它甚至适用于任何其他类型的字符串、dict 等我认为这是最好的方法,一般规则是尽可能避免使用正则表达式
例如
>>> 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(',')]
【讨论】: