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.
you can use regex:
import re
just = 'Standard Price:20000'
price = re.findall("\d+", just)[0]
OR
price = just.split(":")[1]
You can also try:
int(''.join(i for i in just if i.isdigit()))
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'>
>>>
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.
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