Python Program to print which letters are in both the strings

In this simple python program, we need to print which letters are in both the strings. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What are sets in the python program?

In this simple python program on sets, we need to find the letters present in both the strings using sets. A set in python is defined as a collection of iterable data which is unordered. Sets can be represented by the braces which we use to represent the mathematical set. Set values must be unique, which means the set does not have any duplicate values in it. 

Using a set, we can check for a given element that is present in the set using a data structure called has a table, which is much faster than the list. Python elements cannot be changed, which means immutable, but we can add or remove the elements from the set.

How to print which letters are in both the strings using sets?

In this Basic python program on a string, we need to accept two strings from the user using the input function and save that values into two variables. Then we use the sets union function and save those letters which are present in both sets into a list called 'a', list(set(s1)| set(s2)). Then we use a for loop to the end of the list to print every letter in the list.

ALGORITHM

STEP 1: Accept the two strings and save that strings into two variables.

STEP 2: Use the union set operator and save that values into a list.

STEP 3: Use a for loop from the variable 'i' to the length of the list a.

STEP 4: Print each character of the list using the print function in the python program.

Python Source Code

                                          s1=input("Enter a string:")
s2=input("Enter another string:")
a=list(set(s1)| set(s2))
print("The letters present in both strings are:")
for i in a:
    print(i)
                                      

OUTPUT

Enter a string: hello
Enter another string: world
The letters present in both strings are:
l
d
h
e
w
r
o