Python:比较2个字符串,看它们是否包含相同的字母

Python: Compare 2 strings and see if they contain the same letters

这看起来很简单,但我被卡住了。我想要的是查看字符串 (str1) 是否包含第二个字符串 (str2) 中的所有字母。如果 str1 包含所有字母(以任意顺序,任意次数),则 return 为真。如果不是,return 错误。

[注意] str2 不一定要有 str1 的所有字母。

将字符串转换为 set 个对象。

set(str1).issubset(set(str2))

您还可以使用以下替代语法:

set(str1) <= set(str2)

malonge 所述,set() 是进行此类比较的好主意:

a = "abcdefg"
b ="dgggg"

if set(b) & set(a) == set(b) :
    print "foo"
else:
    print "bar"