Python | Consecutive characters frequency
Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till character changes. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + groupby()
This is one of the shorthand with the help of which this task can be performed. In this, we employ groupby() to group consecutives together to perform frequency calculations.
# Python3 code to demonstrate working of # Consecutive characters frequency# Using list comprehension + groupby()from itertools import groupby # initializing stringtest_str = "geekksforgggeeks" # printing original stringprint("The original string is : " + test_str) # Consecutive characters frequency# Using list comprehension + groupby()res = [len(list(j)) for _, j in groupby(test_str)] # printing result print("The Consecutive characters frequency : " + str(res)) |
Output :
The original string is : geekksforgggeeks The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]
Method #2 : Using regex
Another way to solve this problem is using regex. In this we employ regex character finding technique and find count using len().
# Python3 code to demonstrate working of # Consecutive characters frequency# Using regeximport re # initializing stringtest_str = "geekksforgggeeks" # printing original stringprint("The original string is : " + test_str) # Consecutive characters frequency# Using regexres = [len(sub.group()) for sub in re.finditer(r'(.)\1*', test_str)] # printing result print("The Consecutive characters frequency : " + str(res)) |
Output :
The original string is : geekksforgggeeks The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]



