您的位置:首页 > 编程语言 > Python开发

filter digit number in string

2010-04-30 00:46 381 查看
http://stackoverflow.com/questions/1450897/python-removing-characters-except-digits-from-string

 

import re 
re.sub("/D", <
4000
span class="str">"", "aas30dsa20") 
'3020' 

 

/D
matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.

 

Or you can use
filter
, like so (in Python 2k):

filter(lambda x: x.isdigit(), "aas30dsa20") 

Since in Python 3k,
filter
returns an iterator instead of a
list
, you can use the following instead:

>>> ''.join(filter(lambda x: x.isdigit(), "aas30dsa20")) 
'3020' 


s=''.join(i for i in s if i.isdigit()) 

Another generator variant.

 

>>> s = "foo200bar" 
>>> new_s = "".join(i for i in s if i in "0123456789") 

 

>>> text = "9jk78k.9k87h.ji09j9oj" 
>>> print "".join(i for i in text if i in ".0123456789").replace(".",",",1).replace(".","").replace(",",".") 
978.987099 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息