In this tutorial, we are sharing python program to remove duplicate characters from a string. For example, if given String is “aaaaaa” then output should be “a”, because rest of the “a” are duplicates. Similarly, if the input is “abcd” then output should also be “abcd” because there is no duplicate character in this String.
Copy the below python program and execute it to see the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | def removeDuplicate(str, n): # Used as index in the modified string index = 0 # Traverse through all characters for i in range(0, n): # Check if str[i] is present before it for j in range(0, i + 1): if (str[i] == str[j]): break # If not present, then add it to # result. if (j == i): str[index] = str[i] index += 1 return "".join(str[:index]) # Driver code str= "aaaaaa" n = len(str) print(removeDuplicate(list(str), n)) |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.