编写一个Python程序来检查两个字符串是否是变位词。例如,如果一个字符串是由另一个字符串的字符重新排列形成的,那么它就是一个变位词字符串。例如,“triangle”和“integral”都是通过重新排列字符形成的。
Python程序检查两个字符串是否为变位词
在这个示例中,sorted 方法按字母顺序对两个字符串进行排序,if 条件检查两个排序后的字符串是否相等。如果为 True,则这两个字符串是变位词。
str1 = input("Enter the First String = ")
str2 = input("Enter the Second String = ")
if(sorted(str1) == sorted(str2)):
print("Two Strings are Anagrams.")
else:
print("Two Strings are not Anagrams.")

使用 collections 模块的 Counter()
此程序使用 collections 库中的 Counter 来检查两个字符串是否是变位词。
from collections import Counter
str1 = input("Enter the First String = ")
str2 = input("Enter the Second String = ")
if(Counter(str1) == Counter(str2)):
print("Two Strings are Anagrams.")
else:
print("Two Strings are not Anagrams.")
Enter the First String = race
Enter the Second String = care
Two Strings are Anagrams.
Enter the First String = dare
Enter the Second String = care
Two Strings are not Anagrams.