Menu

gitpiper

is_anagram python Code Snippet in 2024

stringintermediate

Last Updated: 17 May 2024

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

python snippet similar to is_anagram For You in May 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️