Is there any way to optimize this code so it can be shorter?
if user_input[0] == "f" or user_input[0:2] == "mu" or user_input[0:2] == "he" or user_input[-1] == "a":
I thought about using a tuple
inputcheck = ('f', 'mu', 'he', 'a')
but then would run into problems when trying to actually check the different options
if user_input == inputcheck #This would of course not work
if user_input[0] == inputcheck #This may work, but 'a' needs to be checked at -1 index of string not at the start
CodePudding user response:
A way to shorten it would be:
if user_input[0] == "f" or user_input[0:2] in ["mu", "he"] or user_input[-1] == "a":
the in
allows checking of the list values
CodePudding user response:
If you don't want to use regex and all you want to check is prefixes and suffixes, you can use str.startswith and str.endswith, e.g.:
if user_input.startswith("mu")...
This way, you don't have to match the substring range to the length of the prefix.
A common way to test if a predicate is true for any of a list of values is using python's builtin any function in conjunction with a generator expression:
if any(user_input.startswith(prefix) for prefix in ["f", "mu", "he"])...
If you need some functionality more than once (as you mentioned in a comment), you can extract it into a function, e.g.:
PREFIXES = ("f", "mu", "he")
SUFFIXES = ("a",)
def check_user_input(user_input: str) -> bool:
return any(user_input.startswith(prefix) for prefix in PREFIXES) or any(
user_input.endswith(suffix) for suffix in SUFFIXES
)
CodePudding user response:
Well, a (dirty) solution may be using regular expressions,
import re
user_input = input()
if re.search(r"^f|^mu|^ha|a$",user_input):
print("works!!")