Remove Adjacent Duplicates

Remove adjacent duplicate characters.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 7 of 14
remove-adjacent-duplicates.py
1# Take string input
2s = input("Enter a string: ")
3
4# Remove adjacent duplicates
5result = ""
6prev_char = None
7for char in s:
8 if char != prev_char:
9 result += char
10 prev_char = char
11
12print(f"Result: {result}")

Output

Enter a string: aabbcc
Result: abc

What's going on

Track previous character and skip duplicates.

Key Concepts:

Track previous character
Add only if different from previous
Removes adjacent duplicates