2009-05-24 281 views
63

我有一個字符串。如何刪除特定字符後的所有文本? (在這種情況下...
意志...變化後的文本,所以我這就是爲什麼我想要的某一個後刪除所有字符。如何刪除python中特定字符後的所有字符?

+5

如果你不知道,這是有道理的,然後更新您的問題以提供您想要執行的具體示例。 – 2009-05-24 22:07:55

回答

118

拆分最多一次,並採取第一塊:

sep = '...' 
rest = text.split(sep, 1)[0] 

你沒有說如果分隔符不存在會發生什麼。在這種情況下,這個和Alex的解決方案都會返回整個字符串。

+0

請求是「刪除分隔符後面的所有文本」,而不是「獲取」該文本,因此我認爲您需要[0],而不是[-1],在您的其他優秀解決方案中。 – 2009-05-24 22:09:15

7

沒有一個RE(我以爲是你想要的):

def remafterellipsis(text): 
    where_ellipsis = text.find('...') 
    if where_ellipsis == -1: 
    return text 
    return text[:where_ellipsis + 3] 

,或者用RE:您分離

import re 

def remwithre(text, there=re.compile(re.escape('...')+'.*')): 
    return there.sub('', text) 
+0

可能希望使用sep ='...'作爲kwarg,並使用len(sep)而不是對3進行硬編碼,使其稍微適合未來。 – cdleary 2009-05-24 22:49:56

+0

是的,但你需要在每次調用時重新編譯RE,所以性能會受到RE解決方案的影響(對於非RE解決方案沒有真正的區別)。一些普遍性是免費的,有些不是... ;-) – 2009-05-24 22:56:04

+0

@Alex - 感謝您測試解決方案! – 2009-05-24 23:09:49

54

假設您的分隔符是'...',但它可以是任何字符串。

text = 'some string... this part will be removed.' 
head, sep, tail = text.partition('...') 

>>> print head 
some string 

如果沒有找到的分隔符,head將包含所有原始字符串。

在Python 2.5中添加了分區函數。

分區(...) S.partition(SEP) - >(頭,九月,尾)

Searches for the separator sep in S, and returns the part before it, 
the separator itself, and the part after it. If the separator is not 
found, returns S and two empty strings. 
0

重新使用另一種簡單的方法將是

import re, clr 

text = 'some string... this part will be removed.' 

text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1) 

// text = some string 
6

如果你想刪除一個字符串中最後一次出現分隔符後的所有內容,我覺得這個效果很好:

<separator>.join(string_to_split.split(<separator>)[:-1])

例如,如果string_to_split就像root/location/child/too_far.exe的路徑,你只需要在文件夾路徑,您可以通過"/".join(string_to_split.split("/")[:-1])分割,你會得到 root/location/child

相關問題