VOOZH about

URL: https://www.geeksforgeeks.org/python/concatenated-string-uncommon-characters-python/

⇱ Concatenated string with uncommon characters in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Concatenated string with uncommon characters in Python

Last Updated : 14 Jan, 2025

The goal is to combine two strings and identify the characters that appear in one string but not the other. These uncommon characters are then joined together in a specific order. In this article, we'll explore various methods to solve this problem using Python.

Using set symmetric difference 

We can use the symmetric difference operation of the set to pull out all the uncommon characters from both the string and make a string.


Output
fbgc

Explanation:

  • set(s1) and set(2): This converts the string s1 and s2 into a set of unique characters. This removes any duplicates.
  • ^ (Symmetric Difference): This operator performs a symmetric difference between two sets. It returns all elements that are in either set(s1) or set(s2), but not in both.
  • ''.join(): ThisJoins the resulting set of characters back into a string without spaces.

Let's understand different methods to concatenated string with uncommon characters .

Using collections.Counter

collections.Counter count the occurrences of each character in the combined strings, then filters out characters that appear more than once.


Output
cbgf

Explanation:

  • Counter(str1 + str2): This counts all characters in the combined string str1 + str2.
  • List comprehension: This Filters out characters that appear more than once.
  • ''.join(result): This combines the filtered characters into a string.

Using Dictionary

This method uses a dictionary to manually count the frequency of characters in the combined strings, then filters out those that appear only once.


Output
cbgf

Explanation:

  • Frequency dictionary: It is used to count the occurrences of each character in the combined strings s1 + s2.
  • f[ch] == 1): This filters out characters that appear only once.
  • ''.join(res): This joins the filtered characters into a final string.

Using two pass filtering

This method identifies common characters between two strings and then filters them out in separate passes. It is simple but less efficient due to the extra overhead of processing the strings twice.


Output
cbgf

Explanation:

  • set(s1) & set(s2): This finds the intersection of s1 and s2, i.e., the common characters.
  • Two-pass filtering: This filters the characters in both strings by checking if they are not in the common set.
Comment