Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract number from end of the string

I have a string like "Titile Something/17". I need to cut out "/NNN" part which can be 3, 2, 1 digit number or may not be present.

How you do this in python? Thanks.

like image 486
Croll Avatar asked Oct 17 '25 18:10

Croll


1 Answers

You don't need RegEx here, simply use the built-in str.rindex function and slicing, like this

>>> data = "Titile Something/17"
>>> data[:data.rindex("/")]
'Titile Something'
>>> data[data.rindex("/") + 1:]
'17'

Or you can use str.rpartition, like this

>>> data.rpartition('/')[0]
'Titile Something'
>>> data.rpartition('/')[2]
'17'
>>> 

Note: This will get any string after the last /. Use it with caution.

If you want to make sure that the split string is actually full of numbers, you can use str.isdigit function, like this

>>> data[data.rindex("/") + 1:].isdigit()
True
>>> data.rpartition('/')[2].isdigit()
True
like image 62
thefourtheye Avatar answered Oct 20 '25 06:10

thefourtheye