In this tutorial, we will learn how to check if two strings are anagrams in Python. We will cover the basic concept of anagrams and implement a function to perform the check.
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' and 'silent' are anagrams.
The syntax to check if two strings are anagrams in Python is:
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)
We can create a function to check if two given strings are anagrams by sorting their characters and comparing the sorted strings.
For example,
are_anagrams
that takes two parameters str1
and str2
.sorted
function to sort the characters of both strings.def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)
# Sample strings
string1 = 'listen'
string2 = 'silent'
# Check if the strings are anagrams
result = are_anagrams(string1, string2)
# Print the result
if result:
print(f'\'{string1}\' and \'{string2}\' are anagrams')
else:
print(f'\'{string1}\' and \'{string2}\' are not anagrams')
'listen' and 'silent' are anagrams