Vincent Morris
Vincent Morris

Reputation: 670

How to test if part of a string is equal to an item in a list in python?

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

Upvotes: 1

Views: 3320

Answers (4)

dawg
dawg

Reputation: 103834

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']

Upvotes: 2

orabis
orabis

Reputation: 2809

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)

Upvotes: 0

panatale1
panatale1

Reputation: 373

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

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19264

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
>>> 

Upvotes: 0

Related Questions