Python Program that Displays which Letters are in the Two Strings but not in Both

PythonServer Side ProgrammingProgramming

When it is required to display the letters that occur in both strings separately, but are not repeated, the user input is taken, and the ‘list’ and ‘set’ are used to achieve the same.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). The ‘list’ method converts a given iterable to a list type.

Python comes with a datatype known as ‘set’. This ‘set’ contains elements that are unique only.

The set is useful in performing operations such as intersection, difference, union and symmetric difference.

Example

Below is a demonstration for the same −

 Live Demo

my_str_1 = input("Enter the first string...")
my_str_2 = input("Enter the second string...")
my_result = list(set(my_str_1)^set(my_str_2))
print("The letters in strings but not in both the strings are :")
for i in my_result:
   print(i)

Output

Enter the first string...Jane
Enter the second string...Kane
The letters in strings but not in both the strings are :
K
J

Explanation

  • liTwo user inputs are taken- the first string and the second string.
  • An intersection operation is performed on the string.
  • This is done after converting the string to a ‘set’ structure.
  • The result of this operation is converted to a list and stored in a variable.
  • It is iterated over and displayed on the console.
raja
Published on 12-Mar-2021 13:00:39
Advertisements