In this tutorial, we will look at how to remove consecutive duplicates from a string in Python with the help of some examples.
How to remove consecutive duplicates from a string?

You can use a loop to iterate over each character in a string and create a new string with the consecutive duplicates removed. The following are the steps –
- Iterate over each character in the string.
- For each character check if it’s the same as the previous character (stored in a variable). If it is, skip to the next iteration, else add the character to our result string.
- Return the result string.
Note that, strings are immutable in Python, thus, you cannot modify the original string but you can create a new string with the consecutive duplicates removed.
You can use the above method in programming languages other than Python (for example, C++, Java, etc.) since it does not use any language-specific functions or constructs.
Let’s write a function in Python to perform the above steps.
# remove consecutive duplicates from string def remove_consec_duplicates(s): new_s = "" prev = "" for c in s: if len(new_s) == 0: new_s += c prev = c if c == prev: continue else: new_s += c prev = c return new_s
Now, let’s apply the above function on the string “aabbbbcccd”.
# string with consecutive duplicates s = "aabbbbcccd" print(s) # remove consecutive duplicates s = remove_consec_duplicates(s) print(s)
Output:
aabbbbcccd abcd
Here we remove consecutive duplicates from string s and store the resulting string back to s. Note that the resulting string does not have any adjacent repeating characters.
Note that this function does not give a string of unique characters from the string rather it removes adjacent repeating characters. For example –
# string with consecutive duplicates s = "aabbcccaaaa" print(s) # remove consecutive duplicates s = remove_consec_duplicates(s) print(s)
Output:
aabbcccaaaa abca
In the above result, you can see that we get 'a'
two times in the resulting string, this is because our objective is to remove consecutive duplicates and not to get unique characters in the string.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.