简体   繁体   中英

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. 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. It is checking condition if keyword0 and keyword1 in list . if keyword0 returns true if keyword0 is not None or not empty string.

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. 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. For example

>>> items = 'Hello, World!'.split()
>>> items
['Hello,', 'World!']
>>> 'Hello' in items
False
>>> 'Hello,' in items
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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