1
A
回答
5
Strip從子串中刪除從任一端發現的任何字符:它不刪除尾隨或前導單詞。
該實施例表明它很好:
x.strip('ab_ch')
'de_fg'
由於字符 「A」, 「B」, 「C」, 「h」 和 「_」 是在刪除的情況下,前導「abc_c 「全部被刪除。其他字符不會被刪除。
如果您想刪除前導或尾隨單詞,我會建議使用re
或startswith/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'
0
在strip方法的文檔中「chars參數是一個字符串,指定要刪除的字符集。這就是爲什麼除「fgh」之外的每個字符都被刪除(包括兩個下劃線)的原因。
0
strip()刪除字符,不是的子字符串。例如:
x.strip('abcde_')
'fgh'
相關問題
- 1. {strip}:如何避免意外刪除空白?
- 2. django strip /刪除/清除值
- 3. 意外刪除mainWindow.xib
- 4. 意外刪除iOS框架
- 5. WPF意外刪除了App.xaml
- 6. 防止意外刪除
- 7. postgresql:意外刪除pg_filenode.map
- 8. 意外刪除laravel.log內容
- 9. .split&.strip刪除空格和標記
- 10. Django - 意外刪除超級用戶
- 11. Jackrabbit版本刪除 - 名稱意外
- 12. 與AnkhSVN意外刪除的文件夾
- 13. 意外地刪除了PostgreqSql目錄
- 14. 檢查是否OU從意外刪除
- 15. 防止從BigCommerce API中意外刪除
- 16. 從MySQL服務器意外刪除表
- 17. WeakReferences,意外的對象刪除
- 18. 谷歌帳號,意外刪除
- 19. 意外刪除後找不到self.tableview
- 20. 刪除方法意外的結果
- 21. 堆棧上的對象意外刪除
- 22. 恢復意外故事板刪除
- 23. '意外'刪除了node_modules文件夾
- 24. PostgreSQL意外刪除用戶postgres
- 25. 權限管理員意外刪除 - sonarqube.com
- 26. 意外陰影和`刪除[符號]`
- 27. 意外的刪除行爲google spreadsheetApp
- 28. mySQL意外的令牌刪除
- 29. XCode - 意外刪除的構建設置
- 30. 刪除導致意外崩潰
我誤解了strip的含義。我試圖剝去一個「字」,這不是什麼地帶。謝謝。 –
@DylanSu,我在這種情況下包含了去除單個單詞的實現。如果需要,採用一個arg列表可以將其擴展爲一般情況。 –