2017-07-07 78 views

回答

5

Strip從子串中刪除從任一端發現的任何字符:它不刪除尾隨或前導單詞。

該實施例表明它很好:

x.strip('ab_ch') 
'de_fg' 

由於字符 「A」, 「B」, 「C」, 「h」 和 「_」 是在刪除的情況下,前導「abc_c 「全部被刪除。其他字符不會被刪除。

如果您想刪除前導或尾隨單詞,我會建議使用restartswith/endswith

def rstrip_word(str, word): 
    if str.endswith(word): 
     return str[:-len(word)] 
    return str 

def lstrip_word(str, word): 
    if str.startswith(word): 
     return str[len(word):] 
    return str 

def strip_word(str, word): 
    return rstrip_word(lstrip_word(str, word), word) 

刪除多個字

一個非常簡單的實現(貪婪的)從字符串中刪除多個字可以做如下:

def rstrip_word(str, *words): 
    for word in words: 
     if str.endswith(word): 
      return str[:-len(word)] 
    return str 

def lstrip_word(str, *words): 
    for word in words: 
     if str.startswith(word): 
      return str[len(word):] 
    return str 

def strip_word(str, *words): 
    return rstrip_word(lstrip_word(str, *words), *words) 

請注意,這個算法是貪婪,它會找到第一個可能的示例,然後返回:它可能不像您期望的那樣行爲。找到最大長度匹配(雖然不是太棘手)是多一點參與。

>>> strip_word(x, "abc", "adc_") 
'_cde_fgh' 
+2

我誤解了strip的含義。我試圖剝去一個「字」,這不是什麼地帶。謝謝。 –

+1

@DylanSu,我在這種情況下包含了去除單個單詞的實現。如果需要,採用一個arg列表可以將其擴展爲一般情況。 –

0

在strip方法的文檔中「chars參數是一個字符串,指定要刪除的字符集。這就是爲什麼除「fgh」之外的每個字符都被刪除(包括兩個下劃線)的原因。

0

strip()刪除字符,不是的子字符串。例如:

x.strip('abcde_') 
'fgh'