Skip to main content
 首页 » 编程设计

使用 RegEx 列出的 Python 字符串

2025年05月04日22rubylouvre

我想将 mystring 转换成列表。

Input : "(11,4) , (2, 4), (5,4), (2,3) " 
Output: ['11', '4', '2', '4', '5', '4', '2', '3'] 
 
 
 
>>>mystring="(11,4) , (2, 4), (5,4), (2,3)" 
>>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces 
>>>print mystring 
(11,4),(2,4),(5,4),(2,3) 
 
>>>splitter = re.compile(r'[\D]+') 
>>>print splitter.split(mystring) 
['', '11', '4', '2', '4', '5', '4', '2', '3', ''] 

在这个列表中,第一个和最后一个元素都是空的。 (不需要的)

有没有更好的方法来做到这一点。

谢谢。

请您参考如下方法:

>>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ") 
['11', '4', '2', '4', '5', '4', '2', '3']