Python program to check if two strings are an anagram or not :

In this python programming tutorial, we will learn how to check if two strings are an anagram or not.

The user will enter both strings and the program will check if the strings are an anagram or not and print out the result.

Anagram strings :

An anagram string is formed by rearranging the characters of a string. For example, triangle and integral are anagram strings. Both strings should have the same set of characters.

So, if we want to check if two strings are an anagram or not, we will have to check if both strings contain the same characters or not.

Algorithm to check for Anagram strings :

We will use the below algorithm to find out anagram :

1. Take the strings from the user and store them in separate variables.

2. Sort both strings alphabetically.

3. Compare both strings if they are equal or not.

4. If equal, they should be an anagram. Otherwise not.

 

Python program for anagram strings:

#1
def isAnagram(str1,str2):
    return sorted(str1) == sorted(str2)

#2
str1 = input("Enter the string 1 : ")
str2 = input("Enter the string 2 : ")

#3
if isAnagram(str1,str2):
    print("Strings are anagram")
else:
    print("Strings are not anagram")

python check strings anagram

You can also download this program from Github

 

Explanation :

The commented numbers in the above program denote the step number below :

1. isAnagram method is used to check if two strings are an anagram or not. This method takes two strings as parameter and it will return True if strings are an anagram. Else it returns False.

2. Ask the user to enter the strings. Read and store them in str1 and str2 variable.

3. Check if both strings are an anagram or not using isAnagram method and print out the result.

 

Sample Output :

Enter the string 1 : hello
Enter the string 2 : yello
Strings are not anagram

Enter the string 1 : angel
Enter the string 2 : glean
Strings are anagram

Enter the string 1 : stressed
Enter the string 2 : desserts
Strings are anagram

Enter the string 1 : one
Enter the string 2 : two
Strings are not anagram

python example check string anagram

Categories: python

Leave a Reply

Your email address will not be published. Required fields are marked *