Editor

Python Program to Check if Two Strings Are Anagrams

Beginner · Strings

Two strings are anagrams when they use exactly the same letters the same number of times, only in a different order, like "listen" and "silent" or "race" and "care". This program checks two strings by sorting their letters and comparing the results.

Program

check_anagram.py
first = "Listen" # or: first = input("Enter the first string: ")
second = "Silent" # or: second = input("Enter the second string: ")
# Ignore capital letters and spaces
a = first.lower().replace(" ", "")
b = second.lower().replace(" ", "")
print("Sorted letters:", "".join(sorted(a)), "and", "".join(sorted(b)))
if sorted(a) == sorted(b):
print(f'"{first}" and "{second}" are anagrams')
else:
print(f'"{first}" and "{second}" are not anagrams')
Output
Sorted letters: eilnst and eilnst
"Listen" and "Silent" are anagrams

How it works

  1. lower() and replace(" ", "") make the check ignore case and spaces, so phrases like "Dormitory" and "Dirty room" also work.
  2. sorted(a) returns the letters of the string as a sorted list, so both "listen" and "silent" become e, i, l, n, s, t.
  3. If the two sorted lists are equal, the strings use the same letters the same number of times, so they are anagrams.
  4. Strings of different lengths can never be anagrams, and their sorted lists will not match either.

Other ways to write it

Using collections.Counter

Using collections.Counter
from collections import Counter
pairs = [("race", "care"), ("Dormitory", "Dirty room"), ("hello", "world"), ("aab", "abb")]
for first, second in pairs:
a = Counter(first.lower().replace(" ", ""))
b = Counter(second.lower().replace(" ", ""))
result = "anagrams" if a == b else "not anagrams"
print(f"{first} / {second}: {result}")
Output
race / care: anagrams
Dormitory / Dirty room: anagrams
hello / world: not anagrams
aab / abb: not anagrams

Counter counts how many times each letter appears, and two strings are anagrams when the counts match. "aab" and "abb" share the same letters but not the same counts, so they are not anagrams.

Counting letters with a dictionary

Counting letters with a dictionary
def letter_counts(text):
counts = {}
for ch in text.lower():
if ch != " ":
counts[ch] = counts.get(ch, 0) + 1
return counts
first, second = "Night", "Thing"
if letter_counts(first) == letter_counts(second):
print(first, "and", second, "are anagrams")
else:
print(first, "and", second, "are not anagrams")
Output
Night and Thing are anagrams

This does the counting by hand: each letter is a key and its count is the value. Two dictionaries are equal when they have the same keys with the same values, in any order.

Try it yourself

Test the program with "Astronomer" and "Moon starer", then with a pair of your own.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises