String is anagram

OSCC · Python, String · Nov 2, 2020

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

  • Use str.isalnum() to filter out non-alphanumeric characters, str.lower() to transform each character to lowercase.
  • Use collections.Counter to count the resulting characters for each string and compare the results.
from collections import Counter

def is_anagram(s1, s2):
  return Counter(
    c.lower() for c in s1 if c.isalnum()
  ) == Counter(
    c.lower() for c in s2 if c.isalnum()
  )
is_anagram('#anagram', 'Nag a ram!')  # True

Recommended snippets

  • Pad string

    Python, String

    Pads a string on both sides with the specified character, if it's shorter than the specified length.

  • Palindrome

    Python, String

    Checks if the given string is a palindrome.

  • Hex to RGB

    Python, String

    Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.