能有人解释一下这个Python re.sub()的意外输出吗?
我正在使用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'
4
要传递标志,你可以使用 re.compile 这个方法。
expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
7
是的,第四个参数是计数,而不是标志。你是在告诉它要应用这个模式两次(re.IGNORECASE = 2)。