Check String is Anagram in Python

  • Post category:String

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. To check if two strings are anagrams, you can sort the characters in each string and compare the sorted strings.

Step 1: Create two strings.

str1 = "heart"
str2 = "earth"

print("str1 = ", str1)
print("str1 type = ", type(str1))

print("str2 = ", str2)
print("str2 type = ", type(str2))

Step 2: Check if string is anagram or not

if sorted(str1) == sorted(str2):
    print("Anagram")
else:
    print("Not Anagram")
str1 =  heart
str1 type =  <class 'str'>
str2 =  earth
str2 type =  <class 'str'>
Anagram

Free resources to learn advanced skills: AiHints and CodeAllow