Python Program to Check If Two Strings are Anagram – 2023

Hey guys, in this blog we will see a Python Program to Check If Two Strings are Anagram.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Python program to check if two strings are anagrams using sorted()

str1 = "part"
str2 = "trap"

# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()

# check if length is same
if(len(str1) == len(str2)):

    # sort the strings
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)

    # if sorted char arrays are same
    if(sorted_str1 == sorted_str2):
        print(str1 + " and " + str2 + " are anagram.")
        print(str1 + " and " + str2 + " are not anagram.")

    print(str1 + " and " + str2 + " are not anagram.")


part and trap are anagram.

  • First, of all, we are calculating the lengths of both strings.
  • If they are equal then we will proceed further else we will print they are not Anagrams.
  • If the lengths are equal then we will simply sort both the strings and check if the resultant 2 strings are equal or not.
  • If the resultant strings are the same that means both the words are anagrams else not.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 521

Leave a Reply

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