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

Python Check Whether Two Strings Consist of the Same Characters

Python Check Whether Two Strings Consist of the Same Characters

Document Object Reference Manual Python3 Examples

Description: in Python, we can determine whether two strings consist of the same characters by comparing their sorted results. If the sorted results of the two strings are identical, they contain the same characters, just possibly in a different order.

Example

def

are_anagrams

(

str1

,

str2

)

:

   

return

sorted

(

str1

)

==

sorted

(

str2

)

Testing

str1

=

"listen"

str2

=

"silent"

print

(

are_anagrams

(

str1

,

str2

)

)

Code analysis:

  1. are_anagrams The function takes two strings str1 and str2 as its argument.
  2. sorted(str1) and sorted(str2) Sort the two strings separately, returning a list of characters.
  3. By comparing the two sorted lists, if they are equal, the two strings consist of the same characters and the function returns True; otherwise, returns False。

Output result:

True

In this example,"listen" and "silent" consist of the same characters, so the output is True。

Document Object Reference Manual Python3 Examples