Write a Python program to create a string from two given strings concatenating uncommon characters of the said strings


The program takes two input strings, s1 and s2, and concatenates their uncommon characters (i.e., characters that appear in one string but not in the other). Here's a step by step explanation of the code:

  • The first two lines define the input strings "s1" and "s2".
  • The next two "print" statements output the original substrings to the console.
  • The next two lines create sets "set1" and "set2" from the input strings "s1" and "s2" respectively. A set is an unordered collection of unique elements. By converting the input strings to sets, the program can efficiently determine the unique characters in each string.
  • The next line calculates the common characters between the two sets using the "&" operator. The result is stored in a list "com_ch".
  • The next line creates a list "res" that contains all characters from "s1" that are not in the "com_ch" list, followed by all characters from "s2" that are not in the "com_ch" list.
  • The last line concatenates all elements in the "res" list into a single string and outputs it to the console using the "join" method.

Source Code

s1 = "ABCPQXYZ"
s2 = "XYNZABMC"
print("Original Substrings s1 :",s1)
print("Original Substrings s2 :",s2)
 
set1 = set(s1) 
set2 = set(s2) 
 
com_ch = list(set1 & set2) 
res = [ch for ch in s1 if ch not in com_ch] + [ch for ch in s2 if ch not in com_ch] 
print("Concatenating uncommon Characters:",''.join(res))

Output

Original Substrings s1 : ABCPQXYZ
Original Substrings s2 : XYNZABMC
Concatenating uncommon Characters: PQNM


Example Programs