[Tutor] substitute using re.sub

Peter Otten __peter__ at web.de
Wed Oct 25 04:55:16 EDT 2017

kumar s via Tutor wrote:

> Hi group, I am trying to substitute in the following way and i cannot.
> Could you point out whats wrong in what i am doing.
>>>> z'.|D'
>>>> re.sub(z,'1',z)'111'
> I just want only  '1' and not '111'.
> I want:>>> re.sub(z,'1',z)'1'
> re.sub is repeatedly inserting 3 times because z has .|D . How can I
> substitute only 1. ThanksKumar

Do you mean

>>> import re
>>> z = r".\D"
>>> re.sub(re.escape(z), "1", z)
>>> re.sub(re.escape(z), "1", r"foo .\D bar .\D baz")
'foo 1 bar 1 baz'

? It works like this: 

>>> print(re.escape(z))

i. e. re.escape() escapes the characters that have a special meaning in a 
regular expression, in your case the dot and the backslash.

More information about the Tutor mailing list