11
votes

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.

8
You know just[0] == 'S' ,right? - jonrsharpe
"".join(re.findall('\d+', just)) to get all numbers from string - itzMEonTV

8 Answers

19
votes

you can use regex:

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

OR

price = just.split(":")[1]
6
votes

You can also try:

int(''.join(i for i in just if i.isdigit()))
4
votes

You could use string.split function.

>>> just='Standard Price:20000'
>>> int(just.split(':')[1])
20000
4
votes

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'>
>>>
3
votes

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.

1
votes

You could use RegEx

>>> import re
>>> just='Standard Price:20000'
>>> re.search(r'\d+',just).group()
'20000'

Ref: \d matches digits from 0 to 9

Note: Your error

just[0] evaluates to S as it is the 0th character. Thus S[1:] returns an empty string that is '', because the string is of length 1 and there are no other characters after length 1

1
votes

A more crude way if you don't want to use regex is to make use of slicing. Please remember that this would work for extracting any number if the structure of the text remains the same.

just = 'Standard Price:20000'
reqChar = len(just) - len('Standard Price:')
print(int(just[-reqChar:]))
>> 20000
0
votes

The clearest way in my opinion is using the re.sub() function:

import re

just = 'Standard Price:20000'
only_number = re.sub('[^0-9]', '', just)
print(only_number)
# Result: '20000'