Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether Two Strings Are Anagrams

Python Check Whether Two Strings Are Anagrams

Document Object Reference Manual Python3 Examples

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

print

(

is_anagram

(

"listen"

,

"silent"

)

)

 

True

print

(

is_anagram

(

"apple"

,

"pale"

)

)

   

False

Code analysis:

  1. str1.replace(" ", "").lower() and str2.replace(" ", "").lower(): strip spaces from the strings and convert them to lowercase, so the comparison ignores case and spaces.
  2. if len(str1) != len(str2):: if the two strings have different lengths, they cannot be anagrams, so return False。
  3. sorted(str1) == sorted(str2): sort both strings; if the sorted results are the same, they are anagrams, so return True; otherwise, returns False。

Output result:

True
False

Document Object Reference Manual Python3 Examples