21

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.

2
  • 1
    You know just[0] == 'S' ,right? Commented Feb 15, 2015 at 13:11
  • "".join(re.findall('\d+', just)) to get all numbers from string Commented Feb 15, 2015 at 13:20

9 Answers 9

40

you can use regex:

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

OR

price = just.split(":")[1]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I prefer this price = just.split(":")[1] because the user might enter "200standard price:3000" and using re might not bring the right result. But using 'spilt()' will bring the right result. What do you think?
from where 200 will come from??,
The user will give the ticket its plan name, he might give it 2000standard price. It will come from the user input. Hope you get my point?
19

You can also try:

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

3 Comments

This strings single digits, not individual numbers.
Don't think so, it will go through finding all the characters that are digits and putting them into a string and casting that string to an int. For example, try "X502YZ", it will return 502. There'd be problems if OP needed to find separate numbers on either side of non-numerics such as "X502Y3" which would return 5023. But this does seem to fulfill OPs requirements.
This helps me in other assignments
8

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

1 Comment

As mentioned by @Guillius this works doesn't work for python 3.x as filter returns an iterator and not string as in python 2.x
8

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 Comment

Thank you for pointing that out. This is one of the changes in python 3.x over python 2.x
4

You could use string.split function.

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

Comments

4

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'

Comments

2

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

Comments

1

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

Comments

0

Not much difference in what you use but avoiding regex saves an extra import (i5-8250U).

import re

def regex():
    dirty = 'Standard Price:20000'
    return re.findall("\\d+", dirty)[0]

def regex_grp():
    dirty = 'Standard Price:20000'
    return re.search(r'\d+', dirty).group()

def isdigit():
    dirty = 'Standard Price:20000'
    return int(''.join(i for i in dirty if i.isdigit()))

def filter_():
    dirty = 'Standard Price:20000'
    return int(''.join(filter(str.isdigit, dirty)))

regex() 1.33 μs ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
regex_grp() 1.4 μs ± 17.9 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
isdigit() 1.73 μs ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
filter_() 1.33 μs ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.