An anagram is a word or phrase formed by rearranging the letters of another word or phrase.
For example, the word “listen” is an anagram of the word “silent”.
In this tutorial, we will learn how to check if two strings are anagrams in Python.
To check if two strings are anagrams, we need to check if they contain the same letters, regardless of their order.
One way to do this is to sort the letters of each string and compare the resulting sorted strings.
Here’s the Python code to check if two strings are anagrams:
def are_anagrams(str1, str2): """Check if two strings are anagrams""" return sorted(str1) == sorted(str2)
This function takes two strings as input and returns True
if they are anagrams, and False
otherwise.
It works by sorting the letters of each string using the sorted()
function, which returns a sorted list of characters.
Then, it compares the sorted strings using the ==
operator.
Let’s test the function with some examples:
print(are_anagrams('listen', 'silent')) # True print(are_anagrams('listen', 'hello')) # False print(are_anagrams('hello', 'llohe')) # True
The first example returns True
because the strings ‘listen’ and ‘silent’ are anagrams.
The second example returns False
because the strings ‘listen’ and ‘hello’ are not anagrams.
The third example returns True
because the strings ‘hello’ and ‘llohe’ are anagrams, even though their letters are in a different order.
In conclusion, checking if two strings are anagrams is a simple task in Python.
By sorting the letters of each string and comparing the resulting sorted strings, we can determine if they contain the same letters, regardless of their order.