In this simple python program, we need to print which letters are common in both the strings. It is a list based python program.
For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:
In this simple python program on strings, 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. The elements cannot be changed or immutable, but we can add or remove the elements from a set. Also, mathematical set operations like union, intersection, etc can be performed on these sets.
In this Basic python program on strings, 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 commn_elems. Then we use a for loop
to the end of the list to print every letter in the list.
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
to traverse the list commn_elems and do step 4
STEP 4: Print each character of the list using the print
function in the python program.
s1=input("Enter a string:")
s2=input("Enter another string:")
commn_elems=list(set(s1)| set(s2))
print("The letters present in both strings are:")
for i in commn_elems:
print(i)
Enter a string: hello Enter another string: world The letters present in both strings are: l d h e w r o