Check if Two Strings Are Anagrams Using Python

Check Anagrams using Python
Check Anagrams using Python

An anagram is a word that forms by rearranging the letters of another word or phrase. For example, the word "anagram" is an anagram of "nagaram." This article explains how to check if two strings are anagrams using Python.

Manual check

We can use the following steps to check if two words are anagrams.

  1. First, we need to remove all the spaces from the strings. This can be done using the replace() method in Python. We can replace all the spaces with an empty string.

    # String Declaration
    string1 = "Ana gram"
    string2 = "Naga ram"
    
    # Removing spaces from the strings
    string1 = string1.replace(" ", "")
    string2 = string2.replace(" ", "")
    
  2. Next, we need to convert both strings to lowercase or uppercase. This is to make sure that the case of the letters does not affect the result of the anagram check. We can use the lower() or upper() method for this.

    # Convert strings to the same case.
    string1 = string1.lower()
    string2 = string2.lower()
    
  3. Now, we need to sort the letters in both strings. This can be done using the sorted() function in Python. The sorted() function returns list of sorted characters in a string.

    # Sort the Letters in the strings
    string1 = sorted(string1)
    string2 = sorted(string2)
    
  4. After sorting the strings, we can compare them to see if they are anagrams. If the sorted strings are equal, then the two original strings are anagrams.

    # Comparing the two strings
    if string1 == string2:
        print("The strings are anagrams.")
    else:
        print("The strings are not anagrams.")
    

Combining all the steps above into a single function

We can combine all these steps in a single function to check if two strings are anagrams.

def is_anagram(string1, string2):
    string1 = string1.replace(" ", "").lower()
    string2 = string2.replace(" ", "").lower()
    
    string1 = sorted(string1)
    string2 = sorted(string2)
    
    if string1 == string2:
        return True
    else:
        return False

print(is_anagram("anagram", "nagaram"))  # True
print(is_anagram("hello", "world"))  # False
💡
Try Geekbits Tools. ( https://geekbits.tools/ )

Check if Two strings are anagrams using the dictionary

Another way to check if two strings are anagrams is to use a dictionary to count the frequency of each character in the strings. We can create two dictionaries, one for each string, and count the number of times each character appears in the string.

def is_anagram(string1, string2):
    string1 = string1.replace(" ", "").lower()
    string2 = string2.replace(" ", "").lower()
    
    # Create dictionaries to store the frequency of each character
    dict1 = {}
    dict2 = {}
    
    # Count the frequency of each character in both strings
    for char in string1:
        if char in dict1:
            dict1[char] += 1
        else:
            dict1[char] = 1

    for char in string2:
        if char in dict2:
            dict2[char] += 1
        else:
            dict2[char] = 1
            
# Compare the two dictionaries
    if dict1 == dict2:
        return True
    else:
        return False

print(is_anagram("anagram", "nagaram"))  # True
print(is_anagram("hello", "world"))  # False

If the dictionaries are equal, then the two original strings are anagrams.

Check if Two strings are anagrams using the Counter class

Another way to check if two strings are anagrams is to use the Counter class from the collections module. The Counter class takes an iterable as input and counts the frequency of each element in the iterable. We can pass each string as input to a Counter object and compare the resulting dictionaries.

from collections import Counter

def is_anagram(string1, string2):
    string1 = string1.replace(" ", "").lower()
    string2 = string2.replace(" ", "").lower()
    
    # Create Counter objects
    counter1 = Counter(string1)
    counter2 = Counter(string2)
    
    if counter1 == counter2:
        return True
    else:
        return False

print(is_anagram("anagram", "nagaram"))  # True
print(is_anagram("hello", "world"))  # False

We can also use the Counter class to compare the frequency of each character in the two strings. If the frequency of the characters is the same in both strings, then the strings are anagrams.

from collections import Counter

def is_anagram(string1, string2):
    string1 = string1.replace(" ", "").lower()
    string2 = string2.replace(" ", "").lower()
    
    # Create Counter objects
    counter1 = Counter(string1)
    counter2 = Counter(string2)
    
    # Compare the frequency of each character
    for char in counter1:
        if counter1[char] != counter2[char]:
            return False
    return True

print(is_anagram("anagram", "nagaram"))  # True
print(is_anagram("hello", "world"))  # False

Ending ...

In conclusion, there are several ways to check if two strings are anagrams using Python. We can sort the strings and compare them, use dictionaries to count the frequency of each character, or use the Counter class from the collections module. Whichever method you choose, remove spaces and convert the strings to the same case before checking for anagrams.

If you still have any questions, drop them in the comments below.

Thanks for reading :)

If you enjoy our content, please consider buying us a coffee to support our work:

Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.