2013-03-20 111 views
1

我有一个包含多个元素,看起来像这样一个巨大的名单:删除所有字母和逗号从字符串

'A.21,48;B.64,91;C.95,125;D.139,166;E.175,200'

我想去除所有字母和; .字符和追加到一个列表,例如该列表看起来像['21','48','64','91','95','125','139','166','175','200']

我试着使用:

import re 
list.append(re.sub("\D","", <the string i am working on>)) 

但[R在这样的列表中结果 - [' 21 48 64 91 95 125 139 166 175 200']

因为我在一个非常大的文件循环内工作,一行代码将真正有用。

谢谢

+0

为了澄清,您希望单独获取数字而不是在一个空格分隔的块中,对吗?你想为文件的每一行添加不同的子列表吗? – 2013-03-20 21:16:00

+0

是的,我希望每个数字都是列表中的一个单独的元素,将它添加到 – 2013-03-20 21:17:47

回答

3

您可以使用re.findall()

>>> import re 
>>> strs='A.21,48;B.64,91;C.95,125;D.139,166;E.175,200' 
>>> re.findall(r"\d+",strs) 
['21', '48', '64', '91', '95', '125', '139', '166', '175', '200'] 

使用re.sub()

>>> re.sub(r"[A-Z;,.]"," ",strs).split() 
['21', '48', '64', '91', '95', '125', '139', '166', '175', '200'] 

帮助(re.findall):

Help on function findall in module re: 

findall(pattern, string, flags=0) 
Return a list of all non-overlapping matches in the string. 

If one or more groups are present in the pattern, return a 
list of groups; this will be a list of tuples if the pattern 
has more than one group. 

Empty matches are included in the result. 
+1

完美!你能向我解释代码吗? – 2013-03-20 21:14:36

+0

[这里](http://docs.python.org/2/library/re.html#re.findall)是解释。 – Mariano 2013-03-20 21:15:42

+0

@ begin.py'\ d +'将匹配字符串中的所有整数,'re.findall'将这些整数项存储在列表中。 – 2013-03-20 21:21:13

相关问题