Check if Two Strings are Anagrams in Python
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" is an anagram of "silent."
To determine if two strings are anagrams, we can follow a systematic approach. Here’s a Python function that efficiently checks if one string is an anagram of another.
Python Function Implementation
def are_anagrams(str1, str2):
"""Check if two strings are anagrams of each other."""
# Remove whitespace and convert to lowercase for uniformity
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Sort both strings and compare
return sorted(str1) == sorted(str2)
# Example usage
if name == "main":
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False
print(are_anagrams("Dormitory", "Dirty room")) # Output: True
Explanation of the Function
1. Input Cleaning: The function begins by removing any whitespace and converting the strings to lowercase. This ensures that the comparison is case-insensitive and ignores spaces.
2. Sorting: Both strings are then sorted. Sorting rearranges the characters in a consistent order, allowing for straightforward comparison.
3. Comparison: Finally, the sorted versions of both strings are compared. If they match, the two strings are anagrams; if not, they are not.
Example Usage
The function can be tested with various pairs of strings. In the example usage provided:
- The first test with "listen" and "silent" returns True as they are anagrams.
- The second test with "hello" and "world" returns False.
- The third test demonstrates that "Dormitory" and "Dirty room" are also anagrams after cleaning.
This function is efficient and easy to understand, making it suitable for various programming tasks involving anagram detection.