w3resource

Python: Create a string from two given strings concatenating uncommon characters of the said strings

Python String: Exercise-70 with Solution

Write a Python program that concatenates uncommon characters from two strings.

Visual Presentation:

Python String:  Create a string from two given strings concatenating uncommon characters of the said strings.

Sample Solution:

Python Code:

# Function to concatenate uncommon characters
def uncommon_chars_concat(s1, s2):

  # Convert strings to sets
  set1 = set(s1)
  set2 = set(s2)

  # Find common characters
  common_chars = list(set1 & set2) 

  # List comprehension to get uncommon chars from each string
  result = [ch for ch in s1 if ch not in common_chars] + [ch for ch in s2 if ch not in common_chars]

  # Join characters into string
  return(''.join(result))

# Test strings
s1 = 'abcdpqr' 
s2 = 'xyzabcd'

# Print original strings
print("Original Substrings:\n",s1+"\n",s2)

# Print message
print("\nAfter concatenating uncommon characters:")

# Print result 
print(uncommon_chars_concat(s1, s2)) 

Sample Output:

Original Substrings:
 abcdpqr
 xyzabcd

After concatenating uncommon characters:
pqrxyz

Flowchart:

Flowchart: Create a string from two given strings concatenating uncommon characters of the said strings

Python Code Editor:

Previous: Write a Python program to find the longest common sub-string from two given strings.
Next: Write a Python program to move all spaces to the front of a given string in single traversal.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/string/python-data-type-string-exercise-70.php