以简单的方式从python字符串中提取数字 [英] extract digits in a simple way from a python string
问题描述
我有一个存储数字和单位的字符串,例如
x='$120'y = '90 华氏度'香蕉 = '200 kgm'橙色 = '300 克'total_weight = 香蕉 + 橙子/1000
例如我想添加权重
total_weight = 200 + 300/1000
谢谢!
我试图提取数字只是为了对这些进行一些操作......知道最简单的方法是什么吗?我只处理这两种格式,即数字位于字符串的开头或结尾......
从字符串中提取数字的最简单方法是使用正则表达式和 findall
.
您可能需要更复杂的东西,但这是一个很好的第一步.
请注意,您仍然需要对结果调用 int
以获得正确的数字类型(而不是另一个字符串):
I have a string that stores a number and a unit for example
x= '$120'
y = ' 90 Degrees F'
banana = '200 kgm'
orange = '300 gm'
total_weight = banana + orange/1000
and for example I want to add the weights
total_weight = 200 + 300/1000
Thanks!
I'm trying to extract the numbers only to do some operations with these... any idea of what the simplest way to do this? I'm only dealing with these two formats i.e. digits are at the begining or at the end of the string...
The simplest way to extract a number from a string is to use regular expressions and findall
.
>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']
It might be that you need something more complex, but this is a good first step.
Note that you'll still have to call int
on the result to get a proper numeric type (rather than another string):
>>> map(int, re.findall('\d+', s))
[300, 200, 439843]
这篇关于以简单的方式从python字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!