How to Check if Two Python Strings are Anagrams

How to Check if Two Python Strings are Anagrams

4 mins read6.7K Views Comment
Updated on Jun 12, 2023 10:57 IST

An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this article, we will discuss different methods to check if two strings are anagram or not.

2022_07_2-15.jpg

Python strings are amongst the most frequently asked questions for beginners in Python programming. Whether you’re polishing your coding skills or preparing for interviews, there are a few common programs you will definitely come across, for example:

In this article, we will focus on another such program – how to determine if two strings are anagrams or not using various methods.

Table of Content

But first, for the unaware, let’s talk about what an anagram is, shall we?

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
3 months
– / –
2 weeks
– / –
16 weeks
β‚Ή1.7 K
3 months
– / –
– / –
β‚Ή4.24 K
2 weeks
β‚Ή3 K
3 weeks
– / –
4 months

What is an Anagram?

An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once. For instance:

2022_07_image-117.jpg

All these are examples of anagrams – each word or phrase has the exact same letters as the other, only arranged differently. Interesting, right?

In Python, two strings can be anagrams if all characters of one string can be rearranged into a sequence resulting in another string. Below, we have discussed different ways in which we can check the same:

What are Perfect Squares?
What are Perfect Squares?
In this article, we will discuss perfect squares, and different methods to check the perfect square and finally, we will use python to determine the number of perfect squares in...read more
What is a Prime Number?
What is a Prime Number?
In this article we have covered the concept of Prime Number in Mathematics. Learn what is a prime number, what are the different prime numbers between 1-100 and 101-1000, and...read more
How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Methods to Check if Two Strings are Anagrams

Method 1 – Sort both strings and compare

This method first converts both input strings to lowercase and then sorts the strings using the sort() method. The resulting strings are then compared and if they match, they are anagrams. It’s as simple as it sounds!


 
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Convert into lowercase and sort
str1 = sorted(str1.lower())
str2 = sorted(str2.lower())
print("String 1 after sorting: ", str1)
print("String 2 after sorting: ", str2)
#Define a function to match strings
def isAnagram():
if (str1 == str2) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
print(isAnagram())
Copy code

Output:

2022_07_image-118.jpg
What is Programming What is Python
What is Data Science What is Machine Learning

Method 2 – Using the counter() method

For this method too, we first convert the strings to lowercase. Then we import the counter from the collections library in Python. We will apply this method to both strings and compare the counters for both strings. If the counters match, the strings are anagrams.


 
from collections import Counter
#Define a function to match counters
def check(str1,str2):
print(Counter(str1))
print(Counter(str2))
if (Counter(str1) == Counter(str2)) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Call the function
check(str1.lower(), str2.lower())
Copy code

Output:

2022_07_image-119.jpg
Bitwise Operators in Python
Bitwise Operators in Python
In this article, we will focus on focus on bitwise operators and understand how they perform computations in Python through examples.
Keywords in Python
Keywords in Python
Python has set of keywords that are reserved words, that can’t be used for variable name, function name, or any other identifiers. In this article, we will briefly discuss all...read more
Python Split() Function for Strings
Python Split() Function for Strings
The Python split() function divides a string into a list of substrings based on a specified delimiter. By default, it splits by any whitespace and returns a list of words....read more

Method 3 – Using lists and append() method

Another method is to declare two empty lists l1 and l2. Both input strings are converted to lowercase and appended to l1 and l2 respectively. The lists are then sorted and compared. If matched, the strings are anagrams.


 
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Declare two empty lists
l1=[]
l2=[]
##Convert first string into lowercase
#append to list 1
#and sort
for i in str1:
l1.append(i.lower())
l1.sort()
##Convert second string into lowercase
#append to list 2
#and sort
for j in str2:
l2.append(j.lower())
l2.sort()
print("List 1 after sorting: ", l1)
print("List 2 after sorting: ", l2)
#Define a function to match lists
def isAnagram():
if (l2 == l2) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
print(isAnagram())
Copy code

Output

2022_07_image-120.jpg
Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Method 4 – Using count arrays

We are already aware that 1-byte (8-bits) character sets can contain 256 characters. So, in this method, we perform the following steps:

  • Create count arrays of size 256 to store the input strings.
  • Initialize the count arrays to 0.
  • Iterate through all characters of the strings.
  • After each iteration, the character count is incremented by one in the corresponding count array.
  • Compare the count arrays. If they match, the strings are anagrams.

 
total_char = 256
#Define a function to check if strings are anagrams
def isAnagram(str1, str2):
#Create two count arrays and initialize all values as 0
count1 = [0] * total_char
count2 = [0] * total_char
#For each character in input strings,
#increment count corresponding to count array
for i in str1:
count1[ord(i)] += 1
for i in str2:
count2[ord(i)] += 1
#Check if strings are of the same length
if len(str1) != len(str2):
return 0
#Compare count arrays
for i in range(total_char):
if count1[i] != count2[i]:
return 0
return 1
#Enter input strings
str1 = str(input ("Enter string 1: ")).lower()
str2 = str(input ("Enter string 2: ")).lower()
#Function call
if isAnagram(str1, str2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
Copy code

Output:

2022_07_image-121.jpg
How to Check if Two Python Strings are Anagrams
How to Check if Two Python Strings are Anagrams
An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this...read more
How to Convert Celsius to FahrenheitΒ in Python
How to Convert Celsius to FahrenheitΒ in Python
One of the most common Python programs for beginners is to convert temperature from Celsius to Fahrenheit and vice versa. This tutorial will help you learn how to perform both...read more
Difference Between List and Tuple in Python
Difference Between List and Tuple in Python
Confused with what list and tuples in Python. Don’t worry the article will clear all your doubts. List and Tuple in Python are the data structures that store and manipulate...read more
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio