You can do this with regular expressions
import re regex = re.compile(r'((.)\2*)') matches = regex.finditer("aaaabbbccddddddddeee") s = "" for match in matches: if len(match.group(0)) > 3: s += str(len(match.group(0)))+"Z"+match.group(0)[0] else: s += match.group(0) print(s)