Python Check Whether Two Strings Consist of the Same Characters
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"
(
are_anagrams
(
str1
,
str2
)
)
Code analysis:
are_anagramsThe function takes two stringsstr1andstr2as its argument.sorted(str1)andsorted(str2)Sort the two strings separately, returning a list of characters.- By comparing the two sorted lists, if they are equal, the two strings consist of the same characters and the function returns
True; otherwise, returnsFalse。
Output result:
True
In this example,"listen" and "silent" consist of the same characters, so the output is True。
Python3 Examples