| 
 | 
 
https://blog.csdn.net/yxstory/article/details/78265399 
 
从字符串“127米”中提取数字127:方法一、利用正则表达式 
参考:https://zhidao.baidu.com/question/328905513600600605.html 
用法: 
 
## 总结 
## ^ 匹配字符串的开始。 
## $ 匹配字符串的结尾。 
## \b 匹配一个单词的边界。 
## \d 匹配任意数字。 
## \D 匹配任意非数字字符。 
## x? 匹配一个可选的 x 字符 (换言之,它匹配 1 次或者 0 次 x 字符)。 
## x* 匹配0次或者多次 x 字符。 
## x+ 匹配1次或者多次 x 字符。 
## x{n,m} 匹配 x 字符,至少 n 次,至多 m 次。 
## (a|b|c) 要么匹配 a,要么匹配 b,要么匹配 c。 
## (x) 一般情况下表示一个记忆组 (remembered group)。你可以利用 re.search 函数返回对象的 groups() 函数获取它的值。 
## 正则表达式中的点号通常意味着 “匹配任意单字符” 
 
 
 
 
import re 
 
string = u'127米' 
 
print re.findall(r"\d+\.?\d*", string) 
  
 
 
 
方法二、利用filter(str.isdigit, iterable) 
参考:http://blog.csdn.net/real_tino/article/details/61915570 
 
 
 
 
string = u'127米' 
 
print (filter(str.isdigit, string)) 
  
 
 
bug:TypeError: descriptor 'isdigit' requires a 'str' object but received a 'unicode' 
原因:string不是str类型 
修改为: 
 
 
 
 
string = u'127米' 
 
string2 = string.encode('gbk') 
 
print (type(str)) 
 
print (filter(str.isdigit, string2)) 
  
 
 
结果: 
<type 'str'> 
127 
 
 
注意:要提取的字符串不能命名为str,否则会出现TypeError: isdigit() takes no arguments (1 given) 
因为str和filter里的str重名了。 
---------------------本文来自 晓晓星辰 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yxstory/ar ... 399?utm_source=copy  
 |   
 
 
 
 |