Can anyone explain this unexpected Python output re.sub ()?

I use Python 2.6 and get [what I think] unexpected output from 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'

If this result is expected, what is its logic?

+3
source share
3 answers

Yes, the fourth parameter is the count, not the flags. You say you apply the pattern twice (re.IGNORECASE = 2).

+7
source

To pass flags, you can use re.compile

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

, . 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

0

Source: https://habr.com/ru/post/1713744/


All Articles