re.sub replacement text \-escapes woe

Peter Otten __peter__ at web.de
Sat Feb 14 01:33:46 CET 2004


Peter Otten wrote:

> 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)

re.sub(r'([${}\\])', r'\\\1', s)

Either that or I'm slash-blind tonight...

Peter



More information about the Python-list mailing list