In Python, there’s a fairly straightforward way to create a method that can be used to check strings against each other to see if the two strings are anagrams. Check out the function below to see the method in action — essentially it works by using the “==” comparison operator to see if the strings on either side of the operator are equal to each other when passed through Counter, which will identify if there are any shared characters between the two strings. If the strings are anagrams, the function will return true, and if they’re not, it’ll return false.
from collections import Counter def is_anagram(str1, str2): return Counter(str1) == Counter(str2) >>> is_anagram('cram','carm') True >>> is_anagram('card','cart') False
As you can see in the example above, the method is used by passing two parameters through it, and from there they are compared against each other. This method is particularly useful when trying to see if particular strings are just repeating the same content or holding the same values — especially if these strings are long and hard to keep track of yourself.