Skip to main content
 首页 » 编程设计

python之用字典固定长度 re.sub

2025年05月04日13artech

我有一个字典,所有的键都是三个字母长:threeLetterDict={'abc': 'foo', 'def': 'bar', 'ghi': 'ha' ...}

现在我需要将句子 abcdefghi 翻译成 foobarha。我正在使用 re.sub 尝试下面的方法,但不知道如何将字典放入其中:

p = re.compile('.{3}') # match every three letters 
re.sub(p,'how to put dictionary here?', "abcdefghi") 

谢谢! (无需检查输入长度是否为三的倍数)

请您参考如下方法:

您可以将任何可调用对象传递给 re.sub,因此:

p.sub(lambda m: threeLetterDict[m.group(0)], "abcdefghi") 

It works!