Python Practice › String Programs › Program 75

Remove consecutive duplicates

EasyString Programs · 75 of 106

Write a Python program to collapse consecutive duplicate characters into one.

Advertisement
Input
"xxxxyy"
Output
xyx

Approach

  1. Add a character only if it differs from the last one added.

Solution

Python
text = "xxxxyyxx"result = ""for ch in text:    if not result or ch != result[-1]:        result += chprint(result)
Output
xyx

Line by line

Line 4

not result handles the first character.

Note

Only consecutive repeats are removed, so “xxxxyyxx” becomes “xyx”.

Learn the concept

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

More string programs

← All 106 String Programs

Leave a Comment