Anagram Checker – 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.

The task is to create a Python function that checks if two given strings are anagrams of each other. For instance, the strings “listen” and “silent” are anagrams.

Implementation

def are_anagrams(str1, str2):
    # Remove spaces and convert to lowercase
    str1 = str1.replace(" ", "").lower()
    str2 = str2.replace(" ", "").lower()
    
    # Sort the characters of both strings and compare
    return sorted(str1) == sorted(str2)

# Example usage
string1 = "listen"
string2 = "silent"
result = are_anagrams(string1, string2)
print(f"Are '{string1}' and '{string2}' anagrams? {result}")

The function are_anagrams takes two strings as input parameters, str1 and str2. The first step within the function is to preprocess the strings by removing any spaces and converting all characters to lowercase. This ensures that the comparison is case-insensitive and ignores spaces.

Next, the function sorts the characters of both strings using the built-in sorted() function. The sorted() function returns a list of characters in ascending order.

By comparing the sorted lists of both strings, we can determine if they are anagrams. If the sorted lists are equal, the function returns True, indicating that the strings are anagrams; otherwise, it returns False.