[Tutor] substitute using re.sub

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 25 05:21:08 EDT 2017


On 25/10/17 01:23, kumar s via Tutor wrote:
> Hi group, I am trying to substitute in the following way and i cannot. C
> 
>>>> z'.|D'
>>>> re.sub(z,'1',z)'111'

I don't really know what you are doing here.
It looks like the mail system may have stripped some
characters, Did you post in plain text?

Also, in the call to sub() you have z twice which
suggests you are trying to replace the pattern
itself, is that correct? If so then the dot will match
each character in the pattern and so you will get 111.
If you want to match the literal . then you need to
escape it.

re.sub('\.|D','1','.|D')

But that still matches the D too. To match the
literal string you need to escape the | as well:

re.sub('\.\|D),'1','.|D')

At least that's what I think you want?

But in that case a simple string replacement
would be easier.

'.|D'.replace('.|D','1')

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list