On 14.10.16 20:01, Peter Otten wrote:
Lele Gaifax wrote:
So, how am I supposed to achieve the mentioned intent? By doubling the
escape in the replacement?


If there are no escape sequences aimed to be handled by re.sub() you can
escape the replacement wholesale:

re.sub(r'\s+', re.escape(r'\s+'), 'foo bar')
'foo\\s\\+bar'

OK, that probably escaped too much. Second attempt:

re.sub(r'\s+', lambda m: r'\s+', 'foo bar')
'foo\\s+bar'

Better? If that's too much work at runtime:

def double_bs(s): return "\\\\".join(s.split("\\"))
...
re.sub(r'\s+', double_bs(r'\s+'), 'foo bar')
'foo\\s+bar'

Just use s.replace('\\', r'\\').


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to