[英]Checking for a string/keyword in a list
I am currently doing a piece of code for a game which needs to test whether the player's input contains one or two certain strings.我目前正在为一个游戏编写一段代码,该代码需要测试玩家的输入是否包含一个或两个特定的字符串。 I have tried to make sense of a few explanations but they don't talk about exactly what I need and are quite technical.
我试图理解一些解释,但他们并没有确切地谈论我需要什么并且非常技术性。
So far I have used .split()
to put the input into a list and then used if keyword0 and keyword1 in list:
(as I was hoping to make it so two keywords were required) to provoke a response.到目前为止,我已经使用
.split()
将输入放入列表中,然后使用if keyword0 and keyword1 in list:
因为我希望这样做,因此需要两个关键字)来引发响应。 I think this plan may be flawed so could someone suggest a built-in function or general idea that could be used in some way to achieve this?我认为这个计划可能有缺陷,所以有人可以提出一个可以以某种方式用于实现这一目标的内置功能或一般想法吗?
The code if keyword0 and keyword1 in list:
syntax is doing what you want.代码
if keyword0 and keyword1 in list:
语法正在执行您想要的操作。 It is checking condition if keyword0
and keyword1 in list
.它正在检查条件
if keyword0
和keyword1 in list
。 if keyword0
returns true if keyword0 is not None
or not empty string. if keyword0
不是None
或不是空字符串, if keyword0
返回true。
if keyword0 in list and keyword1 in list:
# do your work
pass
OR或者
if all(key in list for key in [keyword0, keyword1]):
# do your work
pass
You can't use你不能用
if keyword0 and keyword1 in list:
As it effectively evaluates to由于它有效地评估为
if (keyword0) and (keyword1 in list):
Evaluating keyword0
as a boolean.将
keyword0
评估为布尔值。 Instead, try:相反,请尝试:
if keyword0 in list and keyword1 in list:
Note though if you're using .split()
, then your string tokens will include things like punctuation which may not be what you want.请注意,如果您使用
.split()
,那么您的字符串标记将包含标点符号之类的内容,这可能不是您想要的。 For example例如
>>> items = 'Hello, World!'.split()
>>> items
['Hello,', 'World!']
>>> 'Hello' in items
False
>>> 'Hello,' in items
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.