Python Program to Check If Two Strings are Anagram

Write a Python program to check if two strings are anagram or not. For example, if one string forms by rearranging the other string characters, it is an anagram string. For instance, both the triangle and integral will form by rearranging the characters.

Python Program to Check If Two Strings are Anagram

In this Python example, the sorted method sorts the two strings in alphabetical order, and the if condition checks whether both the sorted strings are equal or not. If True, two strings are anagrams.

TIP: Please refer to the Python string article and the Python sorted function.

str1 = input("Enter the First String  = ")
str2 = input("Enter the Second String = ")

if(sorted(str1) == sorted(str2)):
    print("Two Strings are Anagrams.")
else:
    print("Two Strings are not Anagrams.")
Program to Check If Two Strings are Anagram

Using collections module Counter()

This program helps to check if two strings are anagrams or not using Counter from the collections library.

from collections import Counter

str1 = input("Enter the First String  = ")
str2 = input("Enter the Second String = ")

if(Counter(str1) == Counter(str2)):
    print("Two Strings are Anagrams.")
else:
    print("Two Strings are not Anagrams.")
Enter the First String  = race
Enter the Second String = care
Two Strings are Anagrams.

Enter the First String  = dare
Enter the Second String = care
Two Strings are not Anagrams.

Use character removal to check if two strings are anagrams

Here, we assign the second string to a list. Next, we use a for loop to iterate over the first string’s characters. The if statement checks whether the character at each iteration is in the list. If so, remove that character. Otherwise, print that it is not an anagram. Refer to Python list.

s1 = "mad"
s2 = "dam"

lst = list(s2)
for ch in s1:
if ch in lst:
lst.remove(ch)
else:
print("Not anagram")
break
else:
print("Anagram")
Anagram

Also Read