Python Program to Check if Two Strings Are Anagrams
Beginner Strings
Checks whether two words or phrases are anagrams, made of exactly the same letters, by sorting the letters of each and comparing them.
Two words are anagrams when one is the other with its letters in a different order: "listen" and "silent" both have one each of e, i, l, n, s and t. Phrases can be anagrams too, when spaces and capitals don't count, as with "The eyes" and "they see". Sorting the letters of both into alphabetical order turns the question into a plain comparison: anagrams give the same sorted letters.
Program
def is_anagram(first, second):
"""True if first and second use exactly the same letters."""
# Capitals and spaces don't count
first = first.lower().replace(" ", "")
second = second.lower().replace(" ", "")
return sorted(first) == sorted(second)
print("listen and silent:", is_anagram("listen", "silent"))
print("The eyes and they see:", is_anagram("The eyes", "they see"))
print("apple and paper:", is_anagram("apple", "paper"))
Open in the editor Download anagram_check.py
Output
listen and silent: True
The eyes and they see: True
apple and paper: False
How it works
Step through the program line by line: each step below shows up as its line runs.
- Both texts go into lower case and lose their spaces, so
The eyesbecomestheeyes. A capital or a space shouldn't make two texts different. -
sorted()puts the letters of each text in alphabetical order, as a list (lists). Texts with the same letters, each the same number of times, give the same list, whatever order the letters started in. - The program checks two words that are anagrams, two phrases that are, and two words that aren't.
| Text | Lower case, no spaces | Sorted |
|---|---|---|
listen |
listen |
e i l n s t |
silent |
silent |
e i l n s t |
The eyes |
theeyes |
e e e h s t y |
they see |
theysee |
e e e h s t y |
apple |
apple |
a e l p p |
paper |
paper |
a e p p r |
apple and paper have the same length and four letters in common, but apple has an l where paper has an r.
Other ways to write it
With collections.Counter
Counter, from the collections module, counts how many times each letter appears. Two
texts are anagrams when the counts match. Counting is quicker than sorting for long texts.
from collections import Counter
def is_anagram(first, second):
first = first.lower().replace(" ", "")
second = second.lower().replace(" ", "")
return Counter(first) == Counter(second)
print(is_anagram("Astronomer", "Moon starer"))Counting with a dictionary
Without imports or sorting: each letter of the first text adds 1 to its count, and each letter of the second takes 1
away. all() is true when every count ends at 0, which means the letters were the same.
def is_anagram(first, second):
counts = {}
for letter in first.lower().replace(" ", ""):
counts[letter] = counts.get(letter, 0) + 1
for letter in second.lower().replace(" ", ""):
counts[letter] = counts.get(letter, 0) - 1
return all(count == 0 for count in counts.values())
print(is_anagram("Dusty", "study"))Try it yourself
- Check "Elvis" and "lives", and "night" and "thing".
- Ignore punctuation too, keeping only the letters with
isalpha(), then check "Eleven plus two!" and "Twelve plus one". - Find the anagrams of "listen" in
["enlist", "google", "inlets", "banana", "tinsel"]. There are three. - Print
sorted(first)andsorted(second)to see what is compared.