2013-09-11 39 views
3

我敢肯定這很容易,我知道我可以使用拆分,流行和加入這個。刪除一個字符和字符串的其餘部分的最後一個實例

如果我有一個字符串,如下所示:

foo_bar_one_two_three

有一個更清潔的方式瓦特/正則表達式的返回:foo_bar_one_two?

感謝

+0

我不知道Python,但是在sed中它是's/_ [^ _] * $ //'。 – Beta

+0

你可以像@beta所說的用're'模塊:'re.sub(r'_ [^ _] * $','','foo_bar_one_two_three')'。但我會建議使用@Tadeck來代替。 – zaquest

回答

8
result = my_string.rsplit('_', 1)[0] 

其行爲是這樣的:

>>> my_string = 'foo_bar_one_two_three' 
>>> print(my_string.rsplit('_', 1)[0]) 
foo_bar_one_two 

見爲str.rsplit([sep[, maxsplit]])文件條目。

2

的一種方法是使用rfind得到最後_字符的索引,然後切片串提取字符到這一點:

>>> s = "foo_bar_one_two_three" 
>>> idx = s.rfind("_") 
>>> if idx >= 0: 
...  s = s[:idx] 
... 
>>> print s 
foo_bar_one_two 

你需要檢查rfind調用返回的東西在使用它獲取子字符串之前大於-1,否則它將剝離最後一個字符。

如果必須使用正則表達式(我傾向於更喜歡簡單的情況下,這樣的非正則表達式的解決方案),你可以這樣說:

>>> import re 
>>> s = "foo_bar_one_two_three" 
>>> re.sub('_[^_]*$','',s) 
'foo_bar_one_two' 
0

我所知道的是蟒蛇,我的回答可能是語法有點不對勁,但在Java中,你會怎麼做:在Python

String a = "foo_bar_one_two_three"; 
String[] b = a.split("_"); 
String c = ""; 
for(int i=0; i<b.length-1; a++){ 
    c += b[i]; 
    if(i != b.length-2){ 
     c += "_"; 
    } 
} 
//and at this point, c is "foo_bar_one_two" 

希望split功能的工作方式相同。 :)

編輯:

使用功能的限制部分,你可以這樣做:

String a = "foo_bar_one_two_three"; 
String[] b = a.split("_",StringUtils.countMatches(a,"_")); 
//and at this point, b is the array = [foo,bar,one,two] 
+0

Python更簡潔。你所做的基本上就是''_'。join(a.split('_')[: - 1])''。我認爲你採取的步驟與在幾乎30個字符長的例子中執行的步驟完全相同。 – Tadeck

1

類似的的rsplit解決方案,rpartition也將工作:

result = my_string.rpartition("_")[0] 

你」我們需要留意沒有找到分隔符的情況。在這種情況下,原來的字符串將是在索引2中,不爲0

文檔字符串:

rpartition(...)

S.rpartition(SEP) - >(頭,月,尾)

在S的末尾搜索S中的分隔符,並返回 之前的部分,分隔符本身以及其後的部分。如果找不到 分隔符,則返回兩個空字符串和S.

相關問題