Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract digits in a simple way from a python string [duplicate]

Tags:

python

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...

like image 931
Ka Ra Avatar asked Apr 28 '12 16:04

Ka Ra


People also ask

How do you extract digits from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do you extract a floating number from a string in Python?

To extract a floating number from a string with Python, we call the re. findall method. import re d = re. findall("\d+\.

How do you extract digits?

Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.


2 Answers

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] 
like image 90
senderle Avatar answered Oct 14 '22 13:10

senderle


Without using regex, you can just do:

def get_num(x):     return int(''.join(ele for ele in x if ele.isdigit())) 

Result:

>>> get_num(x) 120 >>> get_num(y) 90 >>> get_num(banana) 200 >>> get_num(orange) 300 

EDIT :

Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):     return float(''.join(ele for ele in x if ele.isdigit() or ele == '.')) 

Result:

>>> get_num('dfgd 45.678fjfjf') 45.678 
like image 37
Akavall Avatar answered Oct 14 '22 15:10

Akavall