如何从 Python 中的字符串中提取数字?

Lew*_*wis -1 python string floating-point int python-3.x

你如何从字符串中提取一个数字来操作它?该数字可以是 anint或 a float。例如,如果字符串是"flour, 100, grams"or"flour, 100.5, grams"然后提取数字100100.5.

代码

string  = "flour, 100, grams"
numbers = [int(x) for x in string.split(",")]
print(numbers)
Run Code Online (Sandbox Code Playgroud)

输出

Traceback (most recent call last):
  File "/Users/lewis/Documents/extracting numbers.py", line 2, in <module>
    numbers = [int(x) for x in string.split(",")]
 File "/Users/lewis/Documents/extracting numbers.py", line 2, in <listcomp>
   numbers = [int(x) for x in string.split(",")]
ValueError: invalid literal for int() with base 10: 'flour'
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 5

给定字符串的结构,当您使用str.split将字符串拆分为三个字符串的列表时,您应该只取三个元素之一:

>>> s = "flour, 100, grams"
>>> s.split(",")
['flour', ' 100', ' grams']
>>> s.split(",")[1] # index the middle element (Python is zero-based)
' 100'
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用float将该字符串转换为数字:

>>> float(s.split(",")[1])
100.0
Run Code Online (Sandbox Code Playgroud)

如果您不能确定字符串的结构,您可以使用re(正则表达式)来提取数字map并将它们全部转换:

>>> import re
>>> map(float, re.findall(r"""\d+ # one or more digits
                              (?: # followed by...
                                  \. # a decimal point 
                                  \d+ # and another set of one or more digits
                              )? # zero or one times""",
                          "Numbers like 1.1, 2, 34 and 15.16.",
                          re.VERBOSE))
[1.1, 2.0, 34.0, 15.16]
Run Code Online (Sandbox Code Playgroud)