Flimm
Flimm

Reputation: 151115

Escaping repl argument of re.sub

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?

Upvotes: 7

Views: 628

Answers (1)

Flimm
Flimm

Reputation: 151115

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'

Upvotes: 9

Related Questions