[英]What is the best way to override the delete function in django python
[英]Python Best Way to Delete matches?
我想從 python 中的一個短語中刪除多個字符串。 例如我要刪除: apple, orange, tomato
如果不寫 10 個這樣的替換,我怎么能輕松做到這一點:
str = str.replace('apple','').replace(....).replace(....)
每當您重復自己時,請考慮使用循環。
for word in ('apple','cherry','tomato','grape'):
str = str.replace(word,'')
而且,順便說一句, str
是變量的一個糟糕的名稱,因為它是一個類型的名稱。
您還可以使用re.sub並列出單詞邊界之間的組中的單詞\b
import re
s = re.sub(r"\b(?:apple|orange|tomato)\b", "", s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.