Daniel Engel
Daniel Engel

Reputation: 158

How to know if a part of my string is in another one

As part of my project, I want to ask the user to enter an order from existing orders in a list.

So this is the problem: If my user writes the order in the input not exactly as its written in the list, how will my program understand it?

In other words, I want to turn this into Python code:

if (part of) string in order_list:

How can I do this?

order = input()
orders_list = ["initiate", "eat", "run", "set coords to"]

#Here is the problem
if order in orders_list:
    #my output

For example, lets say I entered "eating" instead of "eat". How will my code understand that I meant "eat"?

Upvotes: 0

Views: 59

Answers (3)

mozillazg
mozillazg

Reputation: 720

>>> from difflib import get_close_matches
>>> orders_list = ["initiate", "eat", "run", "set coords to"]
>>> get_close_matches('eating', orders_list)
['eat']

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599540

The fact that you are struggling with this should be an indication that your data structure is wrong.

Instead of getting the user to write a single string, get them to enter individual elements and store them separately in a list.

Upvotes: 0

zondo
zondo

Reputation: 20336

You can see if any of your words are contained in the users word like this:

if any(word in order for word in orders_list):
    #my output

Upvotes: 2

Related Questions