Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

I am using Python 2.6 and am getting [what I think is] 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 output is what is expected, what is the logic behind it?

like image 904
kjfletch Avatar asked May 31 '26 13:05

kjfletch


2 Answers

Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2).

like image 194
falstro Avatar answered Jun 03 '26 02:06

falstro


To pass flags you can use re.compile

expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
like image 38
ymv Avatar answered Jun 03 '26 03:06

ymv