我正在使用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'
如果这个输出是预期的,它背后的逻辑是什么?
答案 0 :(得分:7)
是的,第四个参数是count,而不是flags。你告诉它应用模式两次(re.IGNORECASE = 2)。
答案 1 :(得分:4)
要传递标记,您可以使用re.compile
expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
答案 2 :(得分: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'