How to Check if Two Python Strings are Anagrams

# How to Check if Two Python Strings are Anagrams

4 mins read6.7K Views Comment
clickHere
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.

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?

## 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:

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?
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?
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
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.

## 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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: ")) #Convert into lowercase and sortstr1 = sorted(str1.lower())str2 = sorted(str2.lower()) print("String 1 after sorting: ", str1)print("String 2 after sorting: ", str2) #Define a function to match stringsdef isAnagram(): if (str1 == str2) : return "The strings are anagrams." else: return "The strings are not anagrams." print(isAnagram())Copy code```

Output:

### 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 countersdef 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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: ")) #Call the functioncheck(str1.lower(), str2.lower())Copy code```

Output:

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
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
The below article goes through explaining and implementing split function in python with suitable examples.

### 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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: ")) #Declare two empty listsl1=[]l2=[] ##Convert first string into lowercase#append to list 1#and sortfor i in str1: l1.append(i.lower())l1.sort() ##Convert second string into lowercase#append to list 2#and sortfor 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 listsdef isAnagram(): if (l2 == l2) : return "The strings are anagrams." else: return "The strings are not anagrams." print(isAnagram())Copy code```

Output

### 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 anagramsdef 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 stringsstr1 = str(input ("Enter string 1: ")).lower()str2 = str(input ("Enter string 2: ")).lower() #Function callif isAnagram(str1, str2): print("The strings are anagrams.")else: print("The strings are not anagrams.")Copy code```

Output:

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
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
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

## Conclusion

Hope this article will be helpful for you to understand the different ways in which one can check if two Python strings are anagrams or not. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

Top Trending Article

Interview Questions

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