Python Practice › String Programs › Program 102

Collapse repeated characters

EasyString Programs · 102 of 106

Write a Python program to replace each group of repeated characters with a single character.

Advertisement
Input
"aabbccdd"
Output
abcd

Approach

  1. dict.fromkeys keeps one of each in order.

Solution

Python
print("".join(dict.fromkeys("aabbccdd")))
Output
abcd
Note

The result keeps the original order, “abcd”. The original sample’s “cabd” came from using a set, whose order is not defined.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Leave a Comment