Python Determine whether two strings are composed of the same characters

Document 对象参考手册Python3 Examples

Description: In Python, we can determine whether two strings are composed of the same characters by comparing their sorted results. If the sorted results of the two strings are the same, then the characters they contain are the same, just the order may be different.

Example

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

# Test
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))

Code analysis:

  1. are_anagramsThe function accepts two stringsstr1andstr2as parameters.
  2. sorted(str1)andsorted(str2)Sort the two strings respectively, returning a list containing characters.
  3. By comparing these two sorted lists, if they are equal, it indicates that the two strings are composed of the same characters, and the function returnsTrue, otherwise it returnsFalse。

Output result:

True

In this example,"listen"and"silent"are composed of the same characters, so the output result isTrue。

Document 对象参考手册Python3 Examples

Other extensions