Different behaviour of regexp in 3.6.0b2

Serhiy Storchaka storchaka at gmail.com
Sat Oct 15 03:46:28 EDT 2016


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'\\').





More information about the Python-list mailing list