[Tutor] A simple Perl to Python regex xlation question

Gavin Henry ghenry at suretecsystems.com
Thu Apr 21 16:20:35 CEST 2005


On Wednesday 20 Apr 2005 20:07, Kent Johnson wrote:
> Smith, Jeff wrote:
> > What's the quickest (and most Pythonic) way to do the following Perlism:
> > 	$str = s/d+/d/;
> >
> > (i.e. collapsing multiple occurrences of the letter 'd' to just one)
>
> import re
> s = re.sub('d+', 'd', s, 1)
>
> if I understand the perl...this replaces just one occurance of d+.

It means one or more of d.

> If you 
> want to replace all occurances then use
> s = re.sub('d+', 'd', s)
>
>   >>> import re
>   >>> s = 'dddaddddabcdeddd'
>   >>> re.sub('d+', 'd', s, 1)
>
> 'daddddabcdeddd'
>
>   >>> re.sub('d+', 'd', s)
>
> 'dadabcded'
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Kind Regards,

Gavin Henry.

Open Source. Open Solutions(tm).

http://www.suretecsystems.com/


More information about the Tutor mailing list