Write a Python program to remove all consecutive duplicates of a given string


The program uses the "groupby" function from the "itertools" module in Python to remove consecutive duplicates from a given string. The function takes an input string and returns a new string with all consecutive duplicates removed. Here's a step by step explanation of the code:

  • The first line imports the "groupby" function from the "itertools" module.
  • The next line defines the input string "str1" as "AAAABBBBCCCC".
  • The "print" statement outputs the original string to the console.
  • An empty list called "result_str" is created to store the result string.
  • The "for" loop iterates over the elements returned by the "groupby" function applied to the input string "str1".
  • The "groupby" function groups consecutive duplicates together. The loop then gets the key of the group and appends it to the "result_str" list.
  • The last line outputs the final result string to the console, which is the concatenation of all elements in the "result_str" list.

Source Code

from itertools import groupby 
 
str1 = 'AAAABBBBCCCC'
print("Original string:", str1)
result_str = [] 
for (key,group) in groupby(str1): 
	result_str.append(key) 
 
print("After removing consecutive duplicates: ", ''.join(result_str))

Output

Original string: AAAABBBBCCCC
After removing consecutive duplicates:  ABC


Example Programs