Python Program that Displays which Letters are Present in Both the Strings

PythonServer Side ProgrammingProgramming

When it is required to display the letters common to two strings, the ‘set’ method can be used.

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.

Below is a demonstration for the same −

Example

 Live Demo

string_1 = 'hey'
string_2 = 'jane'
print("The first string is :")
print(string_1)
print("The second string is :")
print(string_2)
my_result = list(set(string_1)|set(string_2))
print("The letters are : ")
for i in my_result:
   print(i)

Output

The first string is :
hey
The second string is :
jane
The letters are :
a
y
j
h
e
n

Explanation

  • Two strings are defined, and are displayed on the console.
  • The ‘set’ is used on both these strings, along with the ‘|’ operator.
  • This operation’s data is assigned to a variable. It is then displayed as output on the console.
raja
Published on 11-Mar-2021 12:43:24
Advertisements