Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Remove duplicate characters from a string - Python Program

Example 1 :

text = "programming" result = "".join(sorted(set(text), key=text.index)) print(result)

Output

 
OUTPUT  :
progamin

Example 2 :

def remove_duplicate_characters(input_string): """ Removes duplicate characters from a string while preserving the order of the first occurrence of each character. Args: input_string (str): The string from which to remove duplicates. Returns: str: The string with duplicate characters removed. """ seen_characters = set() result_string = [] for char in input_string: if char not in seen_characters: result_string.append(char) seen_characters.add(char) return "".join(result_string) # Example Usage and Output string1 = "programming" output1 = remove_duplicate_characters(string1) print(f"Original string: '{string1}'") print(f"String after removing duplicates: '{output1}'") string2 = "hello world" output2 = remove_duplicate_characters(string2) print(f"Original string: '{string2}'") print(f"String after removing duplicates: '{output2}'") string3 = "aabbccddeeff" output3 = remove_duplicate_characters(string3) print(f"Original string: '{string3}'") print(f"String after removing duplicates: '{output3}'")

Output

 
OUTPUT  :
Original string: 'programming'
String after removing duplicates: 'progamin'
Original string: 'hello world'
String after removing duplicates: 'helo wrd'
Original string: 'aabbccddeeff'
String after removing duplicates: 'abcdef'

Explanation:

remove_duplicate_characters(input_string) Function:

  • This function takes a single argument, input_string, which is the string to be processed.
  • It initializes an empty set called seen_characters. A set is used because it efficiently stores unique elements and allows for quick lookups (char not in seen_characters).
  • It initializes an empty list called result_string. This list will store the characters in their unique and ordered sequence.
  • The program iterates through each charin the input_string.
  • Inside the loop, it checks if the current charis already present in seen_characters.

If the char is not in seen_characters, it means this is the first occurrence of that character. The character is then appended to result_string, and added to seen_characters to mark it as seen.

  • Finally, "".join(result_string)concatenates the characters in the result_string list back into a single string and returns it.