Check if two words are anagrams using Python
-
Two words or phrases can be considered as anagrams, if both have the same characters arranged in different order.
Example Anagrams:
Cat - Act
Inch - Chin
Listen - SilentAnagramming is the process of finding different words from a given word.
Anagramming is mainly a recreational activity in the form of games and puzzles.
Although some advanced uses are there in fields like psychology. -
Below code checks if two strings are anagrams.
We can use python to check if 2 or more given words are anagrams.
The logic here is very simple.
We just need to sort the characters of the 2 strings in order.
Then check if the strings are same.
If anagrams are split in to multiple words, replace space before doing the comparison.Copiedstr1 = 'Listen' str2 = 'Silent' strtemp1 = str1.lower().replace(" ", "") strtemp2 = str2.lower().replace(" ", "") if( len(strtemp1) != len(strtemp1) ): print("Not an anagram") else: print(sorted(strtemp1)) print(sorted(strtemp2)) if(sorted(strtemp1) == sorted(strtemp2)): print("Both words are anagrams") else: print("Not an anagram")
Both words are anagrams