Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to find exact match in a list and not just contained in a word within list

Tags:

python

I'm trying to find an exact match for a word in a list of words either in a [] list or a list from a text document separated by a word per line. But using "in" returns true if the word is contained in the list of words. I'm looking for an exact match. For example in python 2.7.12:

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

for names in mylist:
    if 'cat' in names:
        print 'Yes it is in list'

this will return true, but I i want it to only be true if it's an exact match. 'cat' should not return true if 'cathrine' is in mylist.

and trying to use "if 'cat' == names:' does't seem to work.

How would I go about returning true only if the string I'm looking for is an exact match of a list of words, and not contained within a word of a list of words?

like image 457
positivetypical Avatar asked Jan 28 '23 08:01

positivetypical


2 Answers

You can use in directly on the list.

Ex:

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

if 'cat' in mylist:
    print 'Yes it is in list'
#Empty


if 'joey' in mylist:
    print 'Yes it is in list'
#Yes it is in list
like image 88
Rakesh Avatar answered Jan 31 '23 07:01

Rakesh


You can use in with if else conditional operator

In [43]: mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

In [44]: 'yes in list ' if 'cat' in mylist else 'not in list'
Out[44]: 'not in list'
like image 25
Roushan Avatar answered Jan 31 '23 08:01

Roushan