Python:剥离除数字以外的所有内容 [英] Python: Strip Everything but Numbers
本文介绍了Python:剥离除数字以外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须从几个字符串中的每一个中提取一个数字(一个测量的时间值).我怎么能优雅地做到这一点?所有数字都是正数,最多有两位小数.(例如:2.3/40.09/101.4 - E 表示法中没有数字).我正在寻找的代码应该做如下伪代码:
<预><代码>>>>花了 2.3 秒".strip(除了.1234567890"之外的所有内容)2.3 解决方案
用正则表达式为数字选择而不是剥离:
导入重新数字 = re.compile(r'\d+(?:\.\d+)?')numbers.findall("花了 2.3 秒")
演示:
<预><代码>>>>进口重新>>>数字 = re.compile(r'\d+(?:\.\d+)?')>>>numbers.findall("花了 2.3 秒")['2.3']这将返回所有匹配项的列表;这也可以让您在字符串中找到多个数字:
<预><代码>>>>numbers.findall("花了 2.3 到 42.31 秒")['2.3', '42.31']I have to extract a number (a measured time value) from each of several strings. How could I do this elegantly? All numbers are positive and have a maximum of two decimal places. (E.g.: 2.3/ 40.09/ 101.4 - no numbers in E notation). The code I am looking for should do something like the following pseudocode:
>>> "It took 2.3 seconds".strip(everything but ".1234567890")
2.3
解决方案
Instead of strip, select for the numbers with a regular expression:
import re
numbers = re.compile(r'\d+(?:\.\d+)?')
numbers.findall("It took 2.3 seconds")
Demo:
>>> import re
>>> numbers = re.compile(r'\d+(?:\.\d+)?')
>>> numbers.findall("It took 2.3 seconds")
['2.3']
This returns a list of all matches; this lets you find multiple numbers in a string too:
>>> numbers.findall("It took between 2.3 and 42.31 seconds")
['2.3', '42.31']
这篇关于Python:剥离除数字以外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文