1

What is the fastest way in Python to replace sequence of 3 and more same characters in utf-8 text?I need to replace sequence of 3 and more same characters with exact 2 characters. I.e.

aaa -> aa 
bbbb -> bb
abbbcd -> abbcd
124xyyyz3 -> 124xyyz3
1
  • 3
    Your last example is wrong
    – jamylak
    May 14, 2013 at 12:32

3 Answers 3

12
>>> import re
>>> re.sub(r'(\w)\1{2,}', r'\1\1', 'aaa')
'aa'
>>> re.sub(r'(\w)\1{2,}', r'\1\1', 'bbbb')
'bb'
7

You can use regular expression:

import re
re.sub(r'(.)\1{2,}', r'\1\1', 'bbbbbaaacc')

Pattern captures any character followed by the same character repeated two or more times and matches this substring. The replacement replaces a matched substring with just two of the captured character. Dot will not replace repeated new lines, use (.|\n) or re.DOTALL flag for that.

It works with Unicode too:

re.sub(r'(.)\1{2,}', r'\1\1', u'жжж')

And if you have a string variable x containing utf-8 text, use x.decode('utf-8').

2
  • 1
    It would be great if downvoters would come back one day and un-downvote if the problem has been solved.
    – glglgl
    May 14, 2013 at 12:40
  • 1
    @glglgl I did come back and I upvoted this a long time ago
    – jamylak
    Jun 29, 2016 at 23:54
1

Although for this specific case I would go for a regular expression, you could also make this generic to operator on arbitrary sequences, eg:

from itertools import groupby, chain, islice

s = 'abaaaaaabbbbbbbbcdcddddde'
print ''.join(chain.from_iterable(islice(g, 2) for k, g in groupby(s)))
# abaabbcdcdde

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.