4

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Croll
  • 3,631
  • 6
  • 30
  • 63

4 Answers4

3

\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'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Nice, but not so readable :) **thefourtheye**'s sample better, how do you think? – Croll Mar 12 '15 at 09:32
  • @DmitrijA fourtheye's sample would work on `"Titile Something/foo"` input also. But i think you want the last part which has zero or upto three digits. – Avinash Raj Mar 12 '15 at 09:34
  • Yes you are correct here. But if there is no number, there is no slash also. For this i have to check result is not `None` before calling `.group()` on it. – Croll Mar 12 '15 at 09:39
  • i think you could easily check whether `re.search` returns a match object or not. – Avinash Raj Mar 12 '15 at 09:47
3

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
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2
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'

~

lunaferie
  • 401
  • 3
  • 7
  • Thanks for input and welcome. But `split()` returns an array of items split by /, this not 100% matches my task. – Croll Mar 12 '15 at 10:44
1

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.

vks
  • 67,027
  • 10
  • 91
  • 124