简体   繁体   中英

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!

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
'2011-is-going-to-be-cool-455'.rstrip('0123456789-')

尝试这个:

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM