假设我有一个像 [cat,hat,mat,ate]
这样的单词列表,并且我想删除像 这样的字符串中的所有字母
到 a
>acatbatmatecatbtmate
(如果字母 a
不在单词列表中)。
在当前步骤中,我可以使用以下代码按单词列表中的单词拆分字符串:
''.join([word.replace('a','')
if word not in ['cat','hat','mat','ate']
else word for word in re.split('(cat|hat|mat|ate)','acatbatmate') ])
我可以使用re.sub(pattern, repl, string)
直接删除字母a
吗?
最佳答案
您可以使用 re
轻松做到这一点,如下所示:
import re
except_contexts = ['cat','hat','mat','ate']
print(re.sub(r'({})|a'.format("|".join(except_contexts)), lambda x: x.group(1) if x.group(1) else '', 'acatbatmate'))
# => catbtmate
请参阅Python 2 demo .
如果您使用的是 Python 3.5+,只需反向引用就更容易了:
import re
except_contexts = ['cat','hat','mat','ate']
print(re.sub(r'({})|a'.format("|".join(except_contexts)), r'\1', 'acatbatmate'))
但是,如果您打算替换该a
,则需要使用 lambda 表达式。
详细信息
r'({})|a'.format("|".join( except_contexts))
看起来像 (cat|hat|mat|ate)|a
正则表达式。它将匹配并将 cat
、hat
等捕获到组 1 中,如果匹配,我们需要替换为该组内容。否则,我们要么替换为空字符串,要么替换为所需的替换。
请参阅regex demo .
关于Python正则表达式: replace a letter if it is not a part of the word in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50743216/