How to Check if Two Strings Are Anagrams Using Python

An anagram is a word, phrase, or name formed by rearranging the letters of another word or phrase. To create an anagram, you use all the original letters exactly once, and the result is usually meaningful or clever. For example, “Earth” and “Heart” are anagrams.

In this blog, I have provided a Python code that checks if two input strings are anagrams. The code works by converting both strings to lowercase, sorting their letters, and then comparing them to determine if they are anagrams.

Here is the Python code to check anagram:

import sys

def is_anagram(s1, s2):
    """
    convert both strings into lower case, sort them, and then compare if they are equal
    """
    return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower())

def main():
    """
    anagram checker in Python
    """
    # provide two strings as command-line arguments
    args = sys.argv
    # check if user provided a value or not
    if len(args) < 3:
        print("please provide two strings to compare")
    else:
        word1, word2 = str(args[1]), str(args[2])
        if is_anagram(word1, word2):
            print(f'"{word1}" and "{word2}" are anagrams')
        else:
            print(f'"{word1}" and "{word2}" are not anagrams')

if __name__ == "__main__":
    main()

Save the code as anagram_checker.py (or any name you like). Run the script by providing two strings as command-line arguments. E.g.

python anagram_checker.py Earth Heart

Please let me know in the comments if you find any errors in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.