# python - python 如何从字符串中提取简单数字表达式数字？

``````
a = str(input("Type in your wavelength:"))

if"mm" in a:

print("Unit = Millimeter")

b = float(a.split()[0])

``````

`b` 中存储像 `567 mm` 这样的简单输入是一个浮动，但我希望能够提取像 `5*10**6 mm` 这样的输入，但它说

``````
could not convert string to float: '5*10**6'.

``````

``````
from ast import literal_eval

import re

pattern = re.compile(r'(.*[d.])s*(D+)')

data = '5 * 10**6 mm'

match = pattern.fullmatch(data)

if not match:

raise ValueError('Invalid Expression')

num, units = match.groups()

num = literal_eval(num)

``````

1.将 `eval` 与 正规表达式 组合

``````
import re

a = str(input("Type in your wavelength:"))

if"mm" in a:

print("Unit = Millimeter")

# After parsing the units,

# Remove anything other than digits, +, -, *,/,. (floats),! (factorial?) and ()

# If you require any other symbols, add them in

pruned_a = re.sub(r'[^0-9*+-/!.()]',"", a)

result = eval(pruned_a)

``````

`result = eval(expression, {'__builtins__': None}, {})`

( 上面的代码来自另一个Stackoverflow答案： 数学表达式评估 --可能还有其他你可能感兴趣的解决方案：

``````
import re

a = str(input("Type in your wavelength:"))

if"mm" in a:

print("Unit = Millimeter")

# After parsing the units,

# Remove anything other than digits, +, -, *,/,. (floats),! (factorial?) and ()

# If you require any other symbols, add them in

pruned_a = re.sub(r'[^0-9*+-/!.()]',"", a)

result = eval(pruned_a, {'__builtins__': None}, {}) #to be extra safe :)

``````