Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only numbers from string in python

Tags:

python

I want to get only the numbers from a string. For example I have something like this

just='Standard Price:20000'

And I only want it to print out

20000

So I can multiply it by any number.

I tried

just='Standard Price:20000'
just[0][1:]

I got

 ''

What's the best way to go about this? I'm a noob.

like image 995
picomon Avatar asked Feb 15 '15 13:02

picomon


4 Answers

you can use regex:

import re
just = 'Standard Price:20000'
price = re.findall("\d+", just)[0]

OR

price = just.split(":")[1]
like image 119
Hackaholic Avatar answered Oct 21 '22 03:10

Hackaholic


You can also try:

int(''.join(i for i in just if i.isdigit()))
like image 14
Kidus Avatar answered Oct 21 '22 04:10

Kidus


If you want to keep it simpler avoiding regex, you can also try Python's built-in function filter with str.isdigit function to get the string of digits and convert the returned string to integer. This will not work for float as the decimal character is filtered out by str.isdigit.

Python Built-in Functions Filter

Python Built-in Types str.isdigit

Considering the same code from the question:

>>> just='Standard Price:20000'
>>> price = int(filter(str.isdigit, just))
>>> price
20000
>>> type(price)
<type 'int'>
>>>
like image 6
Bala TJ Avatar answered Oct 21 '22 03:10

Bala TJ


I think bdev TJ's answer

price = int(filter(str.isdigit, just))

will only work in Python2, for Python3 (3.7 is what I checked) use:

price = int ( ''.join(filter(str.isdigit, just) ) )

Obviously and as stated before, this approach will only yield an integer containing all the digits 0-9 in sequence from an input string, nothing more.

like image 6
Guillius Avatar answered Oct 21 '22 02:10

Guillius