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
Sorted letters: eilnst and eilnst "Listen" and "Silent" are anagrams
How it works
lower()andreplace(" ", "")make the check ignore case and spaces, so phrases like "Dormitory" and "Dirty room" also work.sorted(a)returns the letters of the string as a sorted list, so both "listen" and "silent" become e, i, l, n, s, t.- If the two sorted lists are equal, the strings use the same letters the same number of times, so they are anagrams.
- Strings of different lengths can never be anagrams, and their sorted lists will not match either.
Other ways to write it
Using collections.Counter
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
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.
Related programs
- Check a Palindrome String
- Count the Frequency of Each Character in a String
- Sort Words in Alphabetical Order
- Check if a String Is a Pangram
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
- Count Each Vowel in a String
All Python programs · CBSE class 12 practical file · Python exercises