以简单的方式从python字符串中提取数字 [英] extract digits in a simple way from a python string

查看:101
本文介绍了以简单的方式从python字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储数字和单位的字符串,例如

x='$120'y = '90 华氏度'香蕉 = '200 kgm'橙色 = '300 克'total_weight = 香蕉 + 橙子/1000

例如我想添加权重

total_weight = 200 + 300/1000

谢谢!

我试图提取数字只是为了对这些进行一些操作......知道最简单的方法是什么吗?我只处理这两种格式,即数字位于字符串的开头或结尾......

解决方案

从字符串中提取数字的最简单方法是使用正则表达式和 findall.

<预><代码>>>>进口重新>>>s = '300 克'>>>re.findall('\d+', s)['300']>>>s = '300 gm 200 kgm 一些更多的东西一个数字:439843'>>>re.findall('\d+', s)['300'、'200'、'439843']

您可能需要更复杂的东西,但这是一个很好的第一步.

请注意,您仍然需要对结果调用 int 以获得正确的数字类型(而不是另一个字符串):

<预><代码>>>>map(int, re.findall('\d+', s))[300、200、439843]

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆