1

I'm trying to figure out how to test an item in a list with part of a string. so for example, if a list contains "potatoechips" and i have a string called "potatoe" how can I check if the string is found in an item in the list?

list = ['potatoechips','icecream','donuts']

if 'potatoe' in list:
    print true
else:
    false

4 Answers 4

2

To just test for presence of a sub string in any of the strings in the list, you can use any:

>>> li = ['potatoechips','icecream','donuts']
>>> s="potatoe"
>>> any(s in e for e in li)
True
>>> s="not in li"
>>> any(s in e for e in li)
False

The advantage is any will break on the first True and can be more efficient if the list is long.

You can also join the list together into a string separated by a delimiter:

>>> s in '|'.join(li)
True

The advantage here would be if you have many tests. in for millions of tests is faster than constructing millions of comprehensions for example.

If you want to know which string has the positive, you can use a list comprehension with the index of the string in the list:

>>> li = ['potatoechips','icecream','donuts', 'potatoehash']
>>> s="potatoe"
>>> [(i,e) for i, e in enumerate(li) if s in e]
[(0, 'potatoechips'), (3, 'potatoehash')]

Or, you can use filter if you just want the strings as an alternative:

>>> filter(lambda e: s in e, li)
['potatoechips', 'potatoehash']
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the string.find(sub) method to validate if a substring is in a string:

li = ['potatoechips', 'icecream', 'donuts']
for item in li:
    if item.find('potatoe') > -1:
        return True
else:
    return False

Comments

0

You are checking if 'potatoe' is in the list using in, but that will check if a specific item in the list is exactly 'potatoe'.

Simply iterate over the list and then check:

def stringInList(str, lst):
    for i in lst:
        if str in i:
            return True
    return False

>>> lst = ['potatoechips', 'icecream', 'donuts']
>>> stringInList('potatoe', lst)
True
>>> stringInList('rhubarb', lst)
False
>>> 

Comments

0

It can be done using 'any' and list comprehensions to filter list to similar words.

list = ['potatoechips','icecream','donuts']
m = 'potatoe'
l = any(x for x in list if m in x)
print(l)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.