如何测试用户输入的字符串是否在列表中? [英] How to test if a user inputted string is in a list?

查看:19
本文介绍了如何测试用户输入的字符串是否在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我正在尝试制作一个脚本,让用户选择打开像 Windows 命令提示符这样的程序.由于 Windows 命令提示符也是用cmd"打开的,我希望用户能够同时输入两者并获得相同的结果.

I am new to Python and I am trying to make a script that gets a users choice to open a program like Windows Command Prompt. Since Windows Command Prompt is also opened with 'cmd' I want the user to have the ability to type both and get the same result.

我知道我可以把它放在多个 elif 语句中,但我想知道我是否可以将两个(或更多)放在一个列表中,并让 python 检查用户输入是否在列表中,如果是, 打开程序或做其他事情

I know I can put it in multiple elif statements, but I was wondering if I can just put the two (or more) in a list and have python check if what the user input is in the list, and if it is, open the program or does whatever else

这是一些我一直在研究的测试代码,现在完全被难住了:

here is some test code I have been working on for a bit and am completely stumped at this point:

userInput = input(">")

userList = []
userList.append(userInput)

commandPrompt = ["cmd", "command prompt"]
testList = ["test1", "test2"]

if userList in commandPrompt:
    print("cmd worked")
elif userInput == testList:
    print("testList worked")
else:
    print("Did not work")

print(userList)

抱歉,如果之前有人问过这个问题.我查遍了 Google 和 Stack Overflow,但没有找到任何与我想要做的事情非常相似的文章,也没有解释它是否可行.

Sorry if this question has been asked before. I checked all over Google and Stack Overflow and was not able to find any article quite like what I was wanting to do or explain if it is or is not possible.

推荐答案

假设我理解正确,您正在检查 userList 是否在 commandPrompt 中.但是 commandPrompt 永远不会包含一个列表,所以这永远不会得到满足.

Assuming I understand correctly, you're checking if userList is in commandPrompt. But commandPrompt never contains a list so this won't ever be satisfied.

if userInput in commandPrompt: 感觉它可能是你需要的.您不需要将用户的输入放入列表中.

if userInput in commandPrompt: feels like it might be what you need. You don't need to put the user's input into a list.

这篇关于如何测试用户输入的字符串是否在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆