[英]Python:- Convert a string into list
我有一個字符串,如groups(1,12,23,12)
,我想將其轉換為[1,12, 23, 12]
groups(1,12,23,12)
[1,12, 23, 12]
類的列表。
我嘗試了這段代碼,但是輸出不是例外。
str = 'groups(1,12,23,12)'
lst = [x for x in str]
請告訴我...!
您可以使用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]
對於沒有正則表達式的方法
>>> a = "groups(1,12,23,12)"
>>> a= a.replace('groups','')
>>> import ast
>>> list(ast.literal_eval(a))
[1, 12, 23, 12]
參考:
例如
>>> 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(',')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.