When it is required to split the joined consecutive characters that are similar in nature, the ‘groupby’ method and the ‘join’ method are used.
Example
Below is a demonstration of the same
from itertools import groupby my_string = 'pppyyytthhhhhhhoooooonnn' print("The string is :") print(my_string) my_result = ["".join(grp) for elem, grp in groupby(my_string)] print("The result is :") print(my_result)
Output
The original string is : pppyyytthhhhhhhooonnn The resultant split string is : ['ppp', 'yyy', 'tt', 'hhhhhhh', 'ooo', 'nnn']
Explanation
The required packages are imported into the environment.
A string is defined and it is displayed on the console.
The string is iterated over and it is sorted using the ‘groupby’ method.
It is converted to a list, and is assigned to a variable.
This is displayed as output on the console.