re.sub replacement text \-escapes woe

Peter Otten __peter__ at web.de
Fri Feb 13 19:21:31 EST 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