Home > Software design >  Python checking if one of multiple Strings is in a String
Python checking if one of multiple Strings is in a String

Time:02-26

Just started using Python so I'm a bit clueless about it, but i want to check if the user-input in the command line is one of seven characters. Is there a way to check all cases without having 7 different comparison statements. For example I want to see if string Test is either equal to "I" "B" etc.

CodePudding user response:

You can make a predetermined list and if your input exactly matches something in there you could execute a statement

lst = ['A', 'B', 'C']
user_input = input('Enter your Letter')
if user_input in lst:
     print('True')

CodePudding user response:

You can check if a String is in a list with this Statement

import sys

import sys

if len(sys.argv) > 3:
        if "codeword" in [sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]]:
                print("Yes the codeword is in it!!!")



CodePudding user response:

To expand on answers offered and present an alternative, if you want to check in a case-insensitive way, you could use any:

acceptable_chars = ['I', 'B']
user_input = input('Enter your Letter')

if any(user_input.upper() == ch.upper() for ch in acceptable_chars):
    ...

A little bit more clever option that you probably shouldn't use, but may be educational:

def compose(f, g):
    return lambda x: f(g(x))

if any(map(compose(user_input.upper().__eq__, str.upper), acceptable_chars)):
    ...
  • Related