2017-07-06 22 views

回答

4

我敢肯定有更优雅的解决方案,但是这一个适用于您的具体情况:

s = 'I would like 1.5 cookies please' 

for i in s.split(): 
    try: 
     #trying to convert i to float 
     result = float(i) 
     #break the loop if i is the first string that's successfully converted 
     break 
    except: 
     continue 

print(result) #1.5 

希望它能帮助!

+0

真的很好的答案!不需要'正则表达式'并且可以识别负号和非十进制格式的数字(+1) –

+2

这可以完美地回答这个问题,但对于用户定义的“浮点数”可能有点过于宽泛。用's =“来试试''无限远比3个饼干更好。”'例如:) – pistache

+0

@pistache是​​的,完美的观察,与['nan']相同(https://docs.python.org/3/library/ functions.html#浮动)。我发现用户的问题[这里](https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string)和[这里](https: //stackoverflow.com/questions/385558/extract-float-double-value),他们解决了很多问题。 –

3

你可以找到这个用regex,发现这种模式将只返回字符串,如果它已经在float类型,即十进制fomatting,所以是这样的:

>>> import re 
>>> matches = re.findall("[+-]?\d+\.\d+", "I would like 1.5 cookies please") 

正如你说你只是想第一一个:

>>> matches[0] 
'1.5' 

编辑:增加[+-]?到它的模式,以承认负浮动,建议pistache!

+1

我要添加的唯一东西就是'[+ - ]?'来捕捉符号。 – pistache

+0

@pistache谢谢!我添加了答案=) –

0

我会使用正则表达式。下面也检查负值。你可以使用PyRegex检查正则表达式。

+0

这是非常低效的,为什么你会在搜索模式中包含字符串的其余部分,然后获取捕获组? 're.search(“\ d + \。\ d +”,s)'可以正常工作,不会复制整个输入字符串,而且速度更快(尤其是输入字符串的大小会增加)。 – pistache

1

如果您预计空格隔开的十进制花车,使用str方法和删除-+.

s = 'I would like 1.5 cookies please' 
results = [t for t in s.split() 
      if t.lstrip('+-').replace('.', '', 1).isdigit()] 
print(results[0]) #1.5 

lstrip用于去除仅在文本左侧的标志,并使用第三个参数replace仅替换文本中的一个点。确切的实现取决于你希望如何格式化浮点数(支持符号之间的空白等)。

相关问题