[Tutor] use of raw strings with regular expression patterns

Alan Gauld alan.gauld at yahoo.co.uk
Sun Nov 8 08:45:25 EST 2020


On 08/11/2020 13:28, Manprit Singh wrote:
> s1 = "saaaaregaaaaamaaaa"
> 
>>>> re.sub(r"a+", "", s1)
> 'sregm'
>>>> re.sub(r"a", "", s1)
> 'sregm'
> 
> I have  solved this with two  patterns , one includes a "+"  that means one
> or more repetition of the previous re . I am confused what pattern must be
> chosen for this  particular case?

With regex there is very rarely only one "correct" answer.
They both work so both are correct. as to which is more
efficient, you'd need to time them to find out.

However, the difference is that the first applies a pattern
repeatedly - that's what the + does. The first simply subs
every letter a with a blank. But thee is a big difference that
is hidden in this case because you are deleting characters.

For example, if instead of replacing 'a' with '', you tried replacing
it with 'b' you might get different results. Try it and you will clearly
see the difference.

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