30秒学会 Python 片段 · 2023年12月10日

30秒学会 Python 片段 – String is anagram

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

翻译自:https://www.30secondsofcode.org/python/s/is-anagram