Python Check Whether Two Strings Are Anagrams
An anagram is 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 compositions.
Example
def
is_anagram
(
str1
,
str2
)
:
Strip 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
)
Testing
(
is_anagram
(
"listen"
,
"silent"
)
)
True
(
is_anagram
(
"apple"
,
"pale"
)
)
False
Code analysis:
str1.replace(" ", "").lower()andstr2.replace(" ", "").lower(): strip spaces from the strings and convert them to lowercase, so the comparison ignores case and spaces.if len(str1) != len(str2):: if the two strings have different lengths, they cannot be anagrams, so returnFalse。sorted(str1) == sorted(str2): sort both strings; if the sorted results are the same, they are anagrams, so returnTrue; otherwise, returnsFalse。
Output result:
True
False
Python3 Examples