我有一个字符串:string = "2017.5 is halfway through the year"
。有没有办法从字符串中提取这个"2017.5"
?我尝试使用string.isdigit()
,但这只适用于非浮点数。
发布于 2017-06-08 05:45:20
如果你的浮点数总是用十进制数表示,就像这样
>>> import re
>>> re.findall("\d+\.\d+", "2017.5 is halfway through the year")
['2017.5']
也许就足够了。
对于解析int和float (点分隔符)值:
re.findall( r'\d+\.*\d*', '2017.5 is halfway through the year' )
结果:
['2017.5']
发布于 2017-06-08 05:45:05
下面是一个使用re.match
的示例
>>> import re
>>> ok = '2017.5 and some stuff'
>>> hmm = re.match(r'[0-9\.]+', ok)
>>> hmm.group()
'2017.5'
r'[0-9\.]+'
是一个正则表达式,用于提取与数字和句点匹配的组
发布于 2017-06-08 20:19:07
这只是一个没有正则表达式的脏实现,每句话只有一位数/浮点数:
s = "new 2017.5 is halfway through the year1"
def process(all,new):
def is_float_try(str):
try:
float(str)
return True
except ValueError:
return False
return new if new.isdigit() or is_float_try(new) else all
print reduce(process,s.split(),'')
# 2017.5
https://stackoverflow.com/questions/44427460
复制