Anagram Checker 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”.
Python Program to Check if Two Strings are Anagrams
def are_anagrams(str1, str2):
"""
Check if two strings are anagrams of each other.
Args:
str1 (str): The first string.
str2 (str): The second string.
Returns:
bool: True if the strings are anagrams, False otherwise.
"""
# Remove spaces and convert to lowercase for case-insensitive comparison
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Anagrams must have the same length
if len(str1) != len(str2):
return False
# Sort the characters in each string and compare
return sorted(str1) == sorted(str2)
# Example usage
string1 = "Listen"
string2 = "Silent"
if are_anagrams(string1, string2):
print(f'"{string1}" and "{string2}" are anagrams.')
else:
print(f'"{string1}" and "{string2}" are not anagrams.')
Explanation
The provided Python program defines a function are_anagrams
that checks whether two given strings are anagrams of each other. Here is a step-by-step explanation of the program:
- Function Definition: The
are_anagrams
function takes two string arguments,str1
andstr2
. - Normalization: Both strings are normalized by removing spaces and converting all characters to lowercase to ensure the comparison is case-insensitive and ignores spaces.
- Length Check: If the lengths of the two strings differ, they cannot be anagrams, so the function returns
False
. - Sorting and Comparison: Both strings are sorted alphabetically. If the sorted versions of both strings are equal, then the original strings are anagrams, and the function returns
True
. Otherwise, it returnsFalse
. - Example Usage: An example usage of the
are_anagrams
function is provided where the strings “Listen” and “Silent” are checked. The result is printed based on whether the strings are anagrams or not.