ana
ana

Reputation: 1595

Remove final slash and number in a string in Python

I have strings like these:

text-23

the-text-9

2011-is-going-to-be-cool-455

I need to remove the final -number from the string in Python (and I'm terrible with regular expressions).

Thanks for your help!

Upvotes: 1

Views: 649

Answers (5)

Russ
Russ

Reputation: 11315

In your case, you probably want rpartition:

s1 = "text-23"
s2 = "the-text-9"
s3 = "2011-is-going-to-be-cool-455"

#If you want the final number...
print s1.rpartition("-")[2]
#23

#If you want to strip the final number and dash...
print s2.rpartition("-")[0]
#the-text

#And showing the full output...
#  - Note that it keeps the rest of your string together, unlike split("-")
print s3.rpartition("-")
#('2011-is-going-to-be-cool', '-', '455')

I think this is ever-so-slightly cleaner to read than split("-", 1), since it is exactly what you want to do. Outputs are near identical, except that rpartition's output includes the delimiter.

And, just for kicks, I had a look and rpartition is marginally quicker...

import timeit
print timeit.Timer("'2011-is-going-to-be-cool-455'.rsplit('-', 1)").timeit()
#1.57374787331
print timeit.Timer("'2011-is-going-to-be-cool-455'.rpartition('-')").timeit()
#1.40013813972

print timeit.Timer("'text-23'.rsplit('-', 1)").timeit()
#1.55314087868
print timeit.Timer("'text-23'.rpartition('-')").timeit()
#1.33835101128

print timeit.Timer("''.rsplit('-', 1)").timeit()
#1.3037071228
print timeit.Timer("''.rpartition('-')").timeit()
#1.20357298851

Upvotes: 2

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

I think the .rsplit() method suggested by @ghostdog74 is best; however, here is another option:

for s in myStrings:
    offs = s.rfind('-')
    s = s if offs==-1 else s[:offs]

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342313

assuming all the text you have ends with -number

>>> s="2011-is-going-to-be-cool-455"
>>> s.rsplit("-",1)[0]
'2011-is-going-to-be-cool'

or

>>> iwant=s.rsplit("-",1)
>>> if iwant[-1].isdigit():
...   print iwant[0]
...
2011-is-going-to-be-cool

Upvotes: 5

BoltClock
BoltClock

Reputation: 723468

Try this:

str = re.sub(r'-[0-9]+$', '', str)

Upvotes: 3

Falmarri
Falmarri

Reputation: 48569

'2011-is-going-to-be-cool-455'.rstrip('0123456789-')

Upvotes: 4

Related Questions