Skip to main content
 首页 » 编程设计

Python:- 将字符串转换为列表

2025年05月04日12jillzhang

我有一个像 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]