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 pr
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
You could use string.split
function.
>>> just='Standard Price:20000'
>>> int(just.split(':')[1])
20000
You can also try:
int(''.join(i for i in just if i.isdigit()))
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.
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
just[0]
evaluates to S
as it is the 0
th 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
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'