【问题标题】:Python: Compare 2 strings and see if they contain the same lettersPython:比较两个字符串,看看它们是否包含相同的字母
【发布时间】:2015-02-07 07:06:10
【问题描述】:

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

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

【问题讨论】:

  • 您需要向我们展示您的示例输入以及您已经尝试过的内容!
  • 看起来 set() 在这里可能是一个不错的选择。 docs.python.org/2/library/sets.html
  • 好吧,字符串是来自用户函数(str,str)的输入,然后假设人们会以某种方式比较这些字符串。我真的完全不确定该去哪里,因为我尝试了 if...else 语句和 while 语句,但无法让它工作。

标签: python python-3.x


【解决方案1】:

将字符串转换为set 对象。

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

您也可以使用这种替代语法:

set(str1) <= set(str2)

【讨论】:

    【解决方案2】:

    就像提到的malonge 一样,set() 是进行此类比较的好主意:

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

    【讨论】:

    • 这应该更简单: if set(b) - set(a): print "b contains characters different from a"
    • 同意,但 issubset 将是最 Pythonic 的方式
    • 这行得通!非常感谢!也感谢@malonge!
    猜你喜欢
    • 2014-02-23
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多