Srivatsav
Srivatsav

Reputation: 73

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

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?

Upvotes: 3

Views: 394

Answers (3)

Yemi Adeoye
Yemi Adeoye

Reputation: 21

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

Upvotes: 2

Sharim09
Sharim09

Reputation: 6224

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

Upvotes: 1

Eli Harold
Eli Harold

Reputation: 2301

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)

Upvotes: 3

Related Questions