Python check whether two strings are anagram
Anagram refers to a word or phrase formed by rearranging the same letters. For example, "listen" and "silent" are a pair of anagrams. We can determine whether two strings are anagrams by comparing their letter composition.
Example
def is_anagram(str1, str2):
# Remove spaces and convert strings to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check whether the lengths of the two strings are the same
if len(str1) != len(str2):
return False
# Sort the strings and compare them
return sorted(str1) == sorted(str2)
# Test
print(is_anagram("listen", "silent")) # True
print(is_anagram("triangle", "integral")) # True
print(is_anagram("apple", "pale")) # False
# Remove spaces and convert strings to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check whether the lengths of the two strings are the same
if len(str1) != len(str2):
return False
# Sort the strings and compare them
return sorted(str1) == sorted(str2)
# Test
print(is_anagram("listen", "silent")) # True
print(is_anagram("triangle", "integral")) # True
print(is_anagram("apple", "pale")) # False
Code analysis:
str1.replace(" ", "").lower()andstr2.replace(" ", "").lower()First, remove spaces in the string and convert the string to lowercase to ensure that case and spaces are ignored when comparing.if len(str1) != len(str2):Check whether the lengths of the two strings are the same. If the lengths are different, they cannot be anagrams.sorted(str1) == sorted(str2)Sort the two strings and compare the sorted results. If the sorted strings are identical, then they are anagrams.
Output result:
True True FalseOther extensions
Python3 Examples