Find common characters between two strings in Python
In this tutorial, I’ll discuss how you can find all the common characters between two strings in Python. This can be done in many ways but we’ll do this with the easiest one. For this we’ll use lower(), join() and intersection() method and also sorted() method if you want to print the result in a sorted manner. These are the built-in methods of Python, so you need not to import it.
- join() Method :- join() is a string method. It takes all items in an iterable and returns a string after joining them into one single string. Some examples of the iterable are list, tuple, string, dictionary and set.
- lower() Method :- It does exactly what its name says. It takes a string and returns it by converting all uppercase characters into lowercase.
- sorted() Method :- It is used to sort the elements of a sequence in a specific order (either ascending or descending).
- intersection() Method :- It is used to find all the elements that are common between two given sets.
Now let us see the code and understand how it works:
#giving input of the 1st string and converting it into lower case string1 = "CoDe".lower() #giving input of the 2nd string and converting it into lower case string2 = "SpEeDy".lower() #joining the strings with the join() method #''.join = joining with empty separator #finding all the common characters between these two strings using the intersection() method #finally sorting the result with the sorted() method and printing it print(''.join(sorted(set.intersection(set(string1), set(string2)))))
As you can see we got all the common characters that are present between these two strings.
So I hope now you are very much familiar with the concept of how to find all the common characters between two strings in Python.