Why doesn't ignorecase flag (re.I) work in re.sub()

Seems to me that you should be doing:

import re
print(re.sub('class', 'function', 'Class object', flags=re.I))

Without this, the re.I argument is passed to the count argument.


The flags argument is the fifth one - you're passing the value of re.I as the count argument (an easy mistake to make).


Note for those who still deal with Python 2.6.x installations or older. Python documentation for 2.6 re says:

re.sub(pattern, repl, string[, count])

re.compile(pattern[, flags])

This means you cannot pass flags directly to sub. They can only be used with compile:

regex = re.compile('class', re.I)
regex.sub("function", "Class object")

Tags:

Python

Regex