简体   繁体   English

Python 3:如何在一行代码中比较多个字符串?

[英]Python 3: how to compare multiple strings in one line of code?

I'm trying to make a category select (by text interface) in Python 3, and I was wondering how I can compare if multiple strings are not true, and then print something along the lines of "that is not a valid choice" 我正在尝试在Python 3中选择类别(通过文本界面),我想知道如何比较多个字符串是否不正确,然后按照“这不是有效选择”的字样打印内容

    input("what is your category choice?")
    if categoryChoice != "category1", "category 2", "category 3":
    print("not a valid choice")

I don't understand the syntax for having it check if any of category1, category2, category3, etc is true/false 我不明白让它检查category1,category2,category3等是否为true / false的语法

Use in for containment tests. 使用in为遏制测试。

categoryChoice = input("what is your category choice?")
if categoryChoice not in ("category1", "category 2", "category 3"):
    print("not a valid choice")

http://ideone.com/e6n0Rr http://ideone.com/e6n0Rr


By the way, if you're using Python 2, you should really use raw_input instead of input . 顺便说一句,如果你使用Python 2,你应该使用raw_input而不是input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM