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 differenceWe can use the symmetric difference operation of the set to pull out all the uncommon characters from both the string and make a string.
Python
s1 = 'aacdb'
s2 = 'gafd'
# Find and join uncommon characters
print(''.join(set(s1) ^ set(s2)))
Explanation:
Let's understand different methods to concatenated string with uncommon characters .
Using collections.Countercollections.Counter count the occurrences of each character in the combined strings, then filters out characters that appear more than once.
Python
from collections import Counter
s1 = 'aacdb'
s2 = 'gafd'
f = Counter(s1 + s2)
# Filter and collect characters that appear only once
res = [ch for ch in s1 + s2 if f[ch] == 1]
print(''.join(res))
Explanation:
This method uses a dictionary to manually count the frequency of characters in the combined strings, then filters out those that appear only once.
Python
s1 = 'aacdb'
s2 = 'gafd'
# Initialize an empty dictionary
f = {}
for ch in s1 + s2:
f[ch] = f.get(ch, 0) + 1
# Filter characters that appear only once
res = [ch for ch in s1 + s2 if f[ch] == 1]
print(''.join(res))
Explanation:
f[ch] == 1
): This filters out characters that appear only once.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.
Python
s1 = 'aacdb'
s2 = 'gafd'
c = set(s1) & set(s2)
# Filter out common characters in two passes
res = ''.join([ch for ch in s1 if ch not in c] + [ch for ch in s2 if ch not in c])
print(res)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4