Python to determine whether two strings are anagrams
An anagram refers to a different word or phrase formed by rearranging the same letters. For example, "listen" and "silent" are anagrams. We can determine whether two strings are anagrams by comparing their letter composition.
Example
def is_anagram(str1, str2):
# Remove spaces and convert the string to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# If the two strings have different lengths, return False directly
if len(str1) != len(str2):
return False
# Sort both strings and compare
return sorted(str1) == sorted(str2)
# Test
print(is_anagram("listen", "silent")) # True
print(is_anagram("apple", "pale")) # False
# Remove spaces and convert the string to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# If the two strings have different lengths, return False directly
if len(str1) != len(str2):
return False
# Sort both strings and compare
return sorted(str1) == sorted(str2)
# Test
print(is_anagram("listen", "silent")) # True
print(is_anagram("apple", "pale")) # False
Code analysis:
str1.replace(" ", "").lower()andstr2.replace(" ", "").lower(): Remove spaces in the string and convert it to lowercase to ensure that case and spaces are not considered during comparison.if len(str1) != len(str2):: If the two strings have different lengths, they cannot be anagrams, returnFalse。sorted(str1) == sorted(str2): Sort the two strings. If the sorted results are the same, they are anagrams; returnTrue, otherwise returnFalse。
Output result:
True FalseOther extensions
Python3 Example