An anagram in Python is a word formed by rearranging the letters of another word. In other words, two words are anagrams of each other if they contain the same letters in a different order. In this article, we will discuss a Python program to check whether two strings are anagrams. We will explain the concept of an anagram and how we can use Python to implement this program.
What is an 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. For example, “listen” can be rearranged to form the word “silent”. Both words contain the same letters but in a different order.
Python Program to Check if Two Strings are Anagrams
We can use Python to check if two strings are anagrams or not. There are several ways to implement this program in Python. Here we will discuss the most common approach that involves sorting the letters of both strings and comparing them.
Here’s the Python program to check if two strings are anagrams:
def are_anagrams(str1, str2): # Convert strings to lowercase str1 = str1.lower() str2 = str2.lower() # Sort the letters of both strings str1_sorted = sorted(str1) str2_sorted = sorted(str2) # Compare the sorted strings if str1_sorted == str2_sorted: return True else: return False # Test the function str1 = "listen" str2 = "silent" if are_anagrams(str1, str2): print("The strings are anagrams.") else: print("The strings are not anagrams.")
In this program, we first convert the strings to lowercase using the
lower() method. This is done to ignore the case of the letters while comparing the strings.
We then sort the letters of both strings using the
sorted() method. This sorts the letters in ascending order.
Finally, we compare the sorted strings using the
== operator. If the sorted strings are equal, we return
True, indicating that the strings are anagrams. Otherwise, we return
We discussed the concept of anagrams and how we can use Python to check whether two strings are anagrams. We provided a Python program that uses the sorting approach to implement this functionality. We hope this article has been informative and helps you in your programming journey.
Thanks for reading. Happy coding!