- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Split joined consecutive similar characters
When it is required to split the joined consecutive characters that are similar in nature, the ‘groupby’ method and the ‘join’ method are used.
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)
The original string is : pppyyytthhhhhhhooonnn The resultant split string is : ['ppp', 'yyy', 'tt', 'hhhhhhh', 'ooo', 'nnn']
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.
Kickstart Your Career
Get certified by completing the courseGet Started