簡體   English   中英

在Python中刪除字符串中的最后斜杠和數字

[英]Remove final slash and number in a string in Python

我有這樣的字符串:

文字23

文字9

2011年將變得很酷455

我需要從Python中的字符串中刪除最終的-number(並且使用正則表達式非常糟糕)。

謝謝你的幫助!

假設所有文本以-number結尾

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

要么

>>> 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)

在您的情況下,您可能需要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')

我認為這比split("-", 1)讀起來稍微干凈一點,因為它正是您想要做的。 輸出幾乎相同,除了rpartition的輸出包括定界符。

而且,只是為了踢球,我看看了,rpartition快了一點……

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

我認為@ ghostdog74建議的.rsplit()方法是最好的。 但是,這是另一種選擇:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM