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 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

print

(

is_anagram

(

"listen"

,

"silent"

)

)

 

True

print

(

is_anagram

(

"triangle"

,

"integral"

)

)

 

True

print

(

is_anagram

(

"apple"

,

"pale"

)

)

 

False

Code analysis:

  1. str1.replace(" ", "").lower() and str2.replace(" ", "").lower(): first remove spaces from the strings and convert them to lowercase, so the comparison ignores case and spaces.
  2. if len(str1) != len(str2):: check whether the two strings have the same length; if the lengths differ, they cannot be anagrams.
  3. 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

Document Object Reference Manual Python3 Examples