2010-09-07 46 views
34

結束串我有一大堆串蟒蛇:除去僅在串

他們中的一些有' rec'

我想刪除,只有當那些都是過去的4個字符

所以換句話說

somestring='this is some string rec' 

我希望它是:

somestring='this is some string' 

什麼是python的方式來處理這個?

+0

可能重複的[Python中刪除的字符串的最後3個字符(http://stackoverflow.com/questions/1798465/python-remove-last-3-characters-of-一個字符串) – outis 2012-04-19 22:32:08

+0

可能的重複[如何從Python中的字符串的末尾刪除子字符串?](http://stackoverflow.com/questions/1038824/how-do-i-remove-a-substring- python) – 2015-09-26 21:47:02

回答

48
def rchop(thestring, ending): 
    if thestring.endswith(ending): 
    return thestring[:-len(ending)] 
    return thestring 

somestring = rchop(somestring, ' rec') 
+3

好東西;只需注意隱藏內置的'str' – bernie 2010-09-07 23:47:31

+0

注意和編輯。謝謝。 – 2010-09-07 23:49:18

+4

@Jack,'string'是一個標準庫模塊的名稱,這可能也是一個不好的主意,可能與內置的名字不一樣,......不過,我建議你儘量習慣使用標識符如'thestring','astring'等等,而不是! - )。 – 2010-09-08 00:20:51

4

你可以使用正則表達式,以及:

from re import sub 

str = r"this is some string rec" 
regex = r"(.*)\srec$" 
print sub(regex, r"\1", str) 
+8

捕獲組在這裏是過度殺傷。 'sub('rec $','',str)'工作。 – 2010-09-07 23:39:55

19

既然你已經得到len(trailing)反正(其中trailing是要刪除,如果它的結尾字符串),我會建議避免在這種情況下.endswith會造成的輕微重複工作。當然,代碼的證明是在時間,所以,讓我們做一些測量(命名後,受訪者提出了他們的功能):

import re 

astring = 'this is some string rec' 
trailing = ' rec' 

def andrew(astring=astring, trailing=trailing): 
    regex = r'(.*)%s$' % re.escape(trailing) 
    return re.sub(regex, r'\1', astring) 

def jack0(astring=astring, trailing=trailing): 
    if astring.endswith(trailing): 
     return astring[:-len(trailing)] 
    return astring 

def jack1(astring=astring, trailing=trailing): 
    regex = r'%s$' % re.escape(trailing) 
    return re.sub(regex, '', astring) 

def alex(astring=astring, trailing=trailing): 
    thelen = len(trailing) 
    if astring[-thelen:] == trailing: 
     return astring[:-thelen] 
    return astring 

說,我們已經命名的這條巨蟒文件a.py,它是在當前目錄;現在,...:

$ python2.6 -mtimeit -s'import a' 'a.andrew()' 
100000 loops, best of 3: 19 usec per loop 
$ python2.6 -mtimeit -s'import a' 'a.jack0()' 
1000000 loops, best of 3: 0.564 usec per loop 
$ python2.6 -mtimeit -s'import a' 'a.jack1()' 
100000 loops, best of 3: 9.83 usec per loop 
$ python2.6 -mtimeit -s'import a' 'a.alex()' 
1000000 loops, best of 3: 0.479 usec per loop 

正如你看到的,基於RE-解決方案「絕望勝過」(如當一個「overkills」的問題經常發生 - 原因RE的一個可能有這樣的壞在Python社區代表! - ),儘管@ Jack的評論中的建議比@ Andrew的原創更好。正如預期的那樣,基於字符串的解決方案與我的endswith一樣,使得它比@Jack's具有微不足道的優勢(快15%)。所以,無論是純粹的思路都很好(既簡潔又清晰) - 我更喜歡我的變體,因爲我是一個節儉的人(某些人可能會說,吝嗇;-)人。 「不浪費,想不」 - )

+0

你有什麼空間在導入一個''a.xxx? – Blankman 2010-09-08 15:49:45

+0

@Blankman,這是一個運行Python的bash命令:setup('-s')是一個參數,代碼是另一個參數。每個都被引用,所以我不必擔心它包括空格和/或特殊字符,os課程。你總是用bash中的空格(以及大多數其他shell,包括Windows自己的cmd.exe)分隔參數,所以我很驚訝你的問題!),並引用參數到shell命令以保留每個參數中的空格和特殊字符也絕對不是我稱之爲任何殼的奇特,稀有或高級用法......!) - ) – 2010-09-08 17:30:12

+0

哦,我看到你繞過'endswith',正如我在傑克的答案中提到的那樣。緩存len也避免了Python(和C的!)可怕的通話開銷。 – 2010-09-12 08:12:19

1

至於那種一個襯墊發生器的加入!

test = """somestring='this is some string rec' 
this is some string in the end word rec 
This has not the word.""" 
match = 'rec' 
print('\n'.join((line[:-len(match)] if line.endswith(match) else line) 
     for line in test.splitlines())) 
""" Output: 
somestring='this is some string rec' 
this is some string in the end word 
This has not the word. 
""" 
8

如果速度並不重要,使用正則表達式:

import re 

somestring='this is some string rec' 

somestring = re.sub(' rec$', '', somestring) 
0

使用more_itertools,我們可以rstrip傳遞謂詞的字符串。

安裝

> pip install more_itertools 

代碼

import more_itertools as mit 


iterable = "this is some string rec".split() 
" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "})) 
# 'this is some string' 

" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "})) 
# 'this is some string' 

下面我們通過我們希望從年底到去除所有尾隨項​​目。

有關詳細信息,另請參閱more_itertools docs

0

使用:

somestring.rsplit(' rec')[0]