能有人解释一下这个Python re.sub()的意外输出吗?

3 投票
3 回答
1001 浏览
提问于 2025-04-15 13:13

我正在使用Python 2.6,发现re.sub()的输出结果有点出乎我的意料。

>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'

如果这个输出结果是正常的,那它背后的逻辑是什么呢?

3 个回答

0

如果你在提问后进行了升级,并且你使用的是 Python 2.7 及以上版本,那么你就不需要使用 re.compile 这个功能了。你可以直接调用 sub,并通过命名参数来指定 flags

>>> import re
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', flags=re.IGNORECASE)
'th- c-t s-t -n th- m-t'

参考链接: https://docs.python.org/2/library/re.html#re.sub

4

要传递标志,你可以使用 re.compile 这个方法。

expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
7

是的,第四个参数是计数,而不是标志。你是在告诉它要应用这个模式两次(re.IGNORECASE = 2)。

撰写回答