Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping repl argument of re.sub

Tags:

python

regex

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?

like image 935
Flimm Avatar asked Apr 20 '18 13:04

Flimm


1 Answers

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'
like image 101
Flimm Avatar answered Nov 08 '22 03:11

Flimm