Pass flags
as a keyword argument not positional argument:
>>> re.sub(r'[^ac]', "X", "ABC", flags=re.IGNORECASE)
'AXC'
Looking at the source code,
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count)
it is clear that when you pass re.IGNORECASE
as a positional argument, it is actually getting passed to count
. It can be verified by this error:
>>> re.sub(r'[^ac]', "X", "ABC", re.IGNORECASE, count=2)
Traceback (most recent call last):
File "<ipython-input-82-8b949ec4f925>", line 1, in <module>
re.sub(r'[^ac]', "X", "ABC", re.IGNORECASE, count=2)
TypeError: sub() got multiple values for keyword argument 'count'
So, as re.IGNORECASE
equals 2, you get the output as 'XXC'
(only two items gets replaced).
>>> re.IGNORECASE
2
>>> re.sub(r'[^ac]', "X", "ABC", re.IGNORECASE)
'XXC'
>>> re.sub(r'[^ac]', "X", "ABC", count=2)
'XXC'
>>> re.sub(r'[^ac]', "X", "ABC", 2)
'XXC'