How to remove duplicates only if consecutive in a string? [duplicate]

For a string such as '12233322155552', by removing the duplicates, I can get '1235'.

But what I want to keep is '1232152', only removing the consecutive duplicates.


Solution 1:

import re

# Only repeated numbers
answer = re.sub(r'(\d)\1+', r'\1', '12233322155552')

# Any repeated character
answer = re.sub(r'(.)\1+', r'\1', '12233322155552')

Solution 2:

You can use itertools, here is the one liner

>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'