# Solution 1
def remove_duplicates(s):
"""
Removes repeated consecutive characters in a string
"""
result = ""
for char in s:
if not result or char != result[-1]:
result += char
return result
# Test the function with the provided examples
test1 = "Red Green White"
result1 = remove_duplicates(test1)
print(result1)
test2 = "aabbbcdeffff"
result2 = remove_duplicates(test2)
print(result2)Review: Remove Duplicates
Module 4: IDEs & Tools
Remove Duplicates
Write a Python function to remove repeated consecutive characters and replace them with single letters and return the updated string.
Example:
- Input: (“Red Green White”) -> Output: “Red Gren White”
- Input: (“aabbbcdeffff”) -> Output: “abcdef”
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solution 2
def remove_duplicates(s):
"""
Removes repeated consecutive characters in a string
"""
empty_ls = []
for i in range(0, len(s)-1):
if s[i] != s[i+1]:
empty_ls.append(s[i])
return "".join(empty_ls) + s[-1]
# Test the function with the provided examples
test1 = "Red Green White"
result1 = remove_duplicates(test1)
print(result1)
test2 = "aabbbcdeffff"
result2 = remove_duplicates(test2)
print(result2)