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

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.")
Python Program to Check If Two Strings are Anagram

Using collections module Counter()

This program helps to check if two strings are anagram or not using Counter from 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.
Python Program to Check If Two Strings are Anagram using collections Counter