Python Practice › String Programs › Program 75
Remove consecutive duplicates
Write a Python program to collapse consecutive duplicate characters into one.
Input
"xxxxyy"
Output
xyx
Approach
- Add a character only if it differs from the last one added.
Solution
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.