Python Determine whether two strings are composed of the same characters
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))
return sorted(str1) == sorted(str2)
# Test
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))
Code analysis:
are_anagramsThe function accepts two stringsstr1andstr2as parameters.sorted(str1)andsorted(str2)Sort the two strings respectively, returning a list containing characters.- 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 returns
True, otherwise it returnsFalse。
Output result:
True
In this example,"listen"and"silent"are composed of the same characters, so the output result isTrue。
Python3 Examples