re.sub replacement text \-escapes woe

Peter Otten __peter__ at web.de
Sat Feb 14 01:21:31 CET 2004


Alexander Schmolck wrote:

> Sorry if I missed something obvious, but how do you do this more
> intelligently?
> 
> def escape(s):
>     return re.sub(r'([${}\\])', r'\ \1', s).replace('\\ ', '\\')
> 
> 'as

Interesting. No direct attack, but another workaround:

re.sub(r'([${}\\])', lambda m: '\\' + m.group(), s)

Peter



More information about the Python-list mailing list