[Solved] Count character repeats in Python


You can use itertools.groupby for this:

>>> s = "aaaXXXbbbXXXcccXdddXXXXXeXf"
>>> import itertools
>>> sum(e == 'X' for e, g in itertools.groupby(s))
5

This groups the elements in the iterable — if no key-function is given, it just groups equal elements. Then, you just use sum to count the elements where the key is 'X'.

Or how about regular expressions:

>>> import re
>>> len(re.findall("X+", s))
5

solved Count character repeats in Python