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...
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.
To extract a floating number from a string with Python, we call the re. findall method. import re d = re. findall("\d+\.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With