Python Check Whether Two Strings Are Anagrams
An anagram is 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 compositions.
Example
def
is_anagram
(
str1
,
str2
)
:
Remove spaces and convert the string to lowercase
str1
=
str1.
replace
(
" "
,
""
)
.
lower
(
)
str2
=
str2.
replace
(
" "
,
""
)
.
lower
(
)
Check whether the two strings have the same length
if
len
(
str1
)
!=
len
(
str2
)
:
return
False
Sort the strings and compare
return
sorted
(
str1
)
==
sorted
(
str2
)
Testing
(
is_anagram
(
"listen"
,
"silent"
)
)
True
(
is_anagram
(
"triangle"
,
"integral"
)
)
True
(
is_anagram
(
"apple"
,
"pale"
)
)
False
Code analysis:
str1.replace(" ", "").lower()andstr2.replace(" ", "").lower(): first remove spaces from the strings and convert them to lowercase, so the comparison ignores case and spaces.if len(str1) != len(str2):: check whether the two strings have the same length; if the lengths differ, they cannot be anagrams.sorted(str1) == sorted(str2): sort both strings and compare the sorted results. If the sorted strings are the same, they are anagrams.
Output result:
True
True
False
Python3 Examples