- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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.
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.
Advertisements