【问题标题】:Fail to find multi-strings找不到多字符串
【发布时间】:2018-01-12 09:54:23
【问题描述】:
about_pet = input("A sentence about your pet")
multi = "dog", "cat"
if all(multi) in about_pet:
    print ("wow, you have one more pets!", " Thanking you reading my 
story:) ")
elif "dog" in about_pet:
    print ("Ah, a dog.", " Thanking you reading my story:) ")
elif "cat" in about_pet:
    print ("Oh, a cat.", " Thanking you reading my story:) ")

我不知道如何在输入中搜索两个字符串。以上捕获的是我所做的。

【问题讨论】:

标签: python


【解决方案1】:

所有都在一个可迭代对象上工作,如果可迭代对象中的所有项都为真,则返回真。

multi = ["dog", "cat"]
if all(m in about_pet for m in multi):
    print ("wow, you have one more pets!", " Thanking you reading my story:) ")

【讨论】:

    【解决方案2】:

    您可以在 if 语句中放置一个 if 语句,以便它首先检查句子是否包含单词 cat,然后如果它包含单词,则继续检查它是否还包含单词 dog,以查看两个单词是否都在字符串。

        about_pet = raw_input("A sentence about your pet")
        if "cat" in about_pet:
          if "dog"in about_pet:
            print "wow, you have one more pets! Thanking you reading my story:) "
        elif "dog" in about_pet:
            print "Ah, a dog. Thanking you reading my story:) "
        elif "cat" in about_pet:
            print "Oh, a cat. Thanking you reading my story:) " 
    

    我知道这可能不是最聪明的解决方案,但它很容易理解。 为简化起见,您可以使用and 依次检查它们

        if "cat" in about_pet and "dog" in about_pet:
    

    或:

        if "cat" and "dog" in about_pet:
    

    如果您使用的是 Python 2.7.10,您还需要使用 raw_input 而不是 input,因为在 Python 2.7.10 中 input 只接受整数和浮点数。如果您使用的是 python 2.7.10(就像我一样),我不会在括号中打印,因为它有时会打印出括号。我还建议在用户说他们没有宠物时添加代码,最后使用else。另外,您不必将句子放在单独的语音标记中。我希望这会有所帮助!

    【讨论】:

    • 两个if可以用and代替。如果 about_pet 中的“猫”和 about_pet 中的“狗”
    • @Simon Black 好的,谢谢,是if "cat" in about_pet and "dog" in about_pet" 还是if "cat" and "dog" in about_pet
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2022-01-14
    • 2014-02-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多