【发布时间】:2017-07-06 02:51:56
【问题描述】:
我想使用 Python 3 查找出现在字符串中的第一个浮点数。
我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们对我的情况不起作用。
一个示例字符串是
I would like 1.5 cookies please
【问题讨论】:
标签: python python-3.x floating-point
我想使用 Python 3 查找出现在字符串中的第一个浮点数。
我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们对我的情况不起作用。
一个示例字符串是
I would like 1.5 cookies please
【问题讨论】:
标签: python python-3.x floating-point
我很确定有更优雅的解决方案,但这一个适用于您的具体情况:
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
希望对你有帮助!
您可以使用regex 找到它,注意这个模式只会返回已经是float 类型的子字符串,即十进制格式,所以是这样的:
>>> import re
>>> matches = re.findall("[+-]?\d+\.\d+", "I would like 1.5 cookies please")
正如你所说,你只想要第一个:
>>> matches[0]
'1.5'
编辑:将[+-]? 添加到模式中,以便它识别负浮点数,正如 pistache 推荐的那样!
【讨论】:
[+-]? 来捕获标志。
如果您希望使用空格分隔的十进制浮点数,请使用 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 的第三个参数用于仅替换文本中的一个点。确切的实现取决于您期望浮点数的格式(支持符号之间的空格等)。
【讨论】:
我会使用正则表达式。下面还会检查负值。
import re
stringToSearch = 'I would like 1.5 cookies please'
searchPattern = re.compile(".*(-?[0-9]\.[0-9]).*")
searchMatch = searchPattern.search(stringToSearch)
if searchMatch:
floatValue = searchMatch.group(1)
else:
raise Exception('float not found')
您可以使用PyRegex 来检查正则表达式。
【讨论】:
re.search("\d+\.\d+", s) 工作正常,不会复制整个输入字符串,而且速度更快(尤其是随着输入字符串大小的增长)。