To count the chars in the string, you can use collections.Counter
:
>>> from collections import Counter
>>> counter = Counter("abceeedtyooo")
>>> print(counter)
Counter({'e': 3, 'o': 3, 'a': 1, 'd': 1, 'y': 1, 'c': 1, 'b': 1, 't': 1})
Then you can filter the result as follows:
>>> result = [char for char in counter if counter[char] == 3]
>>> print(result)
['e', 'o']
If you want to match consecutive characters only, you can use regex (cf. re
):
>>> import re
>>> result = re.findall(r"(.)\1\1", "abceeedtyooo")
>>> print(result)
['e', 'o']
>>> result = re.findall(r"(.)\1\1", "abcaaa")
>>> print(result)
['a']
This will also match if the same character appears three consecutive times multiple times (e.g. on "aaabcaaa"
, it will match 'a'
twice). Matches are non-overlapping, so on "aaaa"
it will only match once, but on "aaaaaa"
it will match twice. Should you not want multiple matches on consecutive strings, modify the regex to r"(.)\1\1(?!\1)"
. To avoid matching any chars that appear more than 3 consecutive times, use (.)(?<!(?=\1)..)\1{2}(?!\1)
. This works around a problem with Python's regex module that cannot handle (?<!\1)
.