Reputation: 55
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?
Upvotes: 5
Views: 15476
Reputation: 129
You can use ==
instead of in
mylist = ['cathrine', 'joey', 'bobby', 'fredrick']
for names in mylist:
if names =='cat' :
print('Matched')
else:
print('Not Matched')
I think it will work!
Upvotes: 1
Reputation: 520
@Rakesh Has given a answer to archive you task, This is just to make a correction to your statement.
trying to use "if 'cat' == names:' does't seem to work
actually 'cat' == names
this returns false
the thing is your are missing the else part to catch that
mylist = ['cathrine', 'joey', 'bobby', 'fredrick']
for names in mylist:
if 'cat' == names:
print ('Yes it is in list')
else:
print('not in list')
Upvotes: 1
Reputation: 82755
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
Upvotes: 5
Reputation: 4420
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'
Upvotes: 1