How to find if an input starts with a certain string from a set

Viewed 117

Consider the following code:

my_items = {'apple','banana','orange'}
x = input("Enter a string : ")

I need to check whether the input starts with any one of the strings in the set and execute some code if it is true. For example, if the input is "apple is tasty", then it should execute some code, else just pass. How do I do that?

3 Answers

You can simply use:

my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.startswith(i) for i in my_items)
print(output)

Output:

Enter a string : apple is tasty
True

If you want it to be true regarless of case you can use:

my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.lower().startswith(i.lower()) for i in my_items)
print(output)

You can split x with ' ' (space), so that you can obtain the item at index [0] which is the first word in the string. Then check if it exists in my_items:

splitVar = x.split(' ')
if splitVar[0] in my_items:
    #your code here

You can use if-else

my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
for i in my_items:
    if x.startswith(i):
        #Write Your Code
        break
    else:
        pass

Related