Check whether two strings are anagram of each other using Python 3.x or earlier

In this tutorial, we will learn about a fun concept of strings and its rearrangement. Today we will discuss “Anagram”. You will learn how to check if two strings are anagram of each other or not in Python.

Anagram – Python

Two strings are said to be Anagram of one another when one string after rearranging gets transformed into the second one. This means that the contain alphabets with same letter count.

There can be two different approaches:
1. Sorting the strings and then comparing them.
2. counting the type of distinct letters and then comparing them.

Approach 2 has slightly high time complexity. So we are going to use the time-efficient one i.e. Approach 1.

Python program to check if two strings are anagram

# taking two sample strings 
s1="code"
s2="speedy"
s3="dcoe"
# sorting two strings
s1=sorted(s1)
s2=sorted(s2)
s3=sorted(s3)
# comparing whether two strings after sorting are equal or not
if s1==s2:
    print("The two strings are Anagaram of each other")
else:
    print("The two strings aren't Anagram of each other")   
   
if s1==s3:
    print("The two strings are Anagaram of each other")  
else:
    print("The two strings aren't Anagram of each other")  

Output:

The two strings aren't Anagram of each other
The two strings are Anagaram of each other

The first if-else block checks whether Code and Speedy are anagrams of each other or not. And the condition is evaluated to be False.

It is very important to take into account the Case Sensitivity of the strings while comparing them. If the Case of the letter is different they can’t be considered as Anagrams.

Stay tuned for further blogs, till then you may also learn,

Leave a Reply