I would like to make sure the repl
argument of re.sub
is escape, so that any special sequences like \1
are not interpreted:
>>> repl = r'\1'
>>> re.sub('(X)', repl, 'X')
'X'
>>> re.sub('(X)', desired_escape_function(repl), 'X')
'\\1'
Is there a function that can do this? I know that re.escape
exists, should this be used?
Do not use re.escape
for this purpose. re.escape
is meant to be used in the pattern
argument, not the repl
argument.
Instead, follow the advice of Python's documentation, and just replace all backslashes with two backslashes manually:
>>> repl = r'\1'
>>> re.sub('(X)', repl.replace('\\', '\\\\'), 'X')
'\\1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With