[Tutor] A simple Perl to Python regex xlation question

Kent Johnson kent37 at tds.net
Wed Apr 20 21:07:28 CEST 2005

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+. 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)
  >>> re.sub('d+', 'd', s)


More information about the Tutor mailing list