Reputation: 3791
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.
Upvotes: 4
Views: 4953
Reputation: 401
data = "Titile Something/17"
print data.split("/")[0]
'Titile Something'
print data.split("/")[-1] #last part string after separator /
'17'
or
print data.split("/")[1] # next part after separator in this case this is the same
'17'
when You want add this to the list use strip() to remove newline "\n"
print data.split("/")[-1].strip()
'17'
~
Upvotes: 2
Reputation: 239473
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
Upvotes: 4
Reputation: 67968
I need to cut out "/NNN"
x = "Titile Something/17"
print re.sub(r"/.*$","",x) #cuts the part after /
print re.sub(r"^.*?/","",x) #cuts the part before /
Using re.sub
you can what you want.
Upvotes: 1
Reputation: 174706
\d{0,3}
matches from zero upto three digits. $
asserts that we are at the end of a line.
re.search(r'/\d{0,3}$', st).group()
Example:
>>> re.search(r'/\d{0,3}$', 'Titile Something/17').group()
'/17'
>>> re.search(r'/\d{0,3}$', 'Titile Something/1').group()
'/1'
Upvotes: 3