Python Program to Check If Two Strings are Anagram

Introduction

In this post, I am going to write a python program to check if two strings are anagram or not. Before this, let us understand what is the meaning of anagram.

Also Read: Python Program to Check Armstrong Number

Suppose we have two strings i.e. silent and listen. These two words or strings are different by their meaning as well as their pronaunciation. But if you rearrange them in ascending or descending order, then you will find both the strings are equal.

The silent become “eilnst” and listen will be “eilnst” after rearrangeing them in ascending order.

Now, let us take one more simple example. Suppose we have two strings i.e. abcd and bcad. So these two strings are anagram. How? Because sort them and see these two strings are equal.

Also Read: Python Program to Delete an Element From a Dictionary

I hope you have understood what is anagram. Now, we will see the expected output and then program for the same.

Expected Output

Enter string1 : silent
Enter string2 : listen
silent and listen are Anagram

Python Program to Check If Two Strings are Anagram

# Python Program to Check If Two Strings are Anagram

# This function will check whether two string anangram or not.
def anagram(string1, string2):
    if sorted(string1) == sorted(string2):
        return 'yes'
    else:
        return 'no'


str1 = input("Enter string1 : ")
str2 = input("Enter string2 : ")
result = anagram(str1.lower(), str2.lower())
if result == 'yes':
    print(f"{str1} and {str2} are Anagram")
else:
    print(f"{str1} and {str2} are not Anagram")

I hope you have understood this program. If you have difficulty, please contact me.

Thank you.

Leave a Comment