Reputation: 11
I have been trying different scenarios with the following code and can't seem to get the right code. I am trying to look in a list for a word and return True. The word that I am looking for is "Jack", but the list contain "Jackie" which is incorrect, but the code return True.
def name_finder(listName,name):
if listName.find(name)!= -1:
return True
else:
return False
nameList = "Joshua Diaddigo, Marguerite Murrell, Jackie Elliott"
print(name_finder(nameList,"Jack"))
print("Done!")
Any help would be appreciated even if it is a hint to where to start.
Upvotes: 0
Views: 33
Reputation: 59229
If you're trying to find a whole word in a string, you can use regex with the word boundary symbol, \b
.
import re
def name_finder(names, name):
return (re.search(r'\b%s\b'%re.escape(name), names) is not None)
Upvotes: 1
Reputation: 618
You need to convert your name_list in python's list datatype, You can do that by this way,
nameList = "Joshua Diaddigo, Marguerite Murrell, Jackie Elliott"
nameList = nameList.split(',')
name = "Jack"
def name_finder(nameList,name):
if name in nameList:
return True
else:
return False
I hope this helps.
Upvotes: 0
Reputation: 46921
one way is to use the regex module:
def name_finder(lst, name):
re_str = '(^|\ |,){}($|\ |,)'.format(name)
return re.search(re_str, lst) != None
the regular expression matches <'the beginning of the string' or 'a space' or 'a comma'> followed by the name followed by <'the end of the string' or 'a space' or 'a comma'>. there may be more elegant ways to write a regex for that...
Upvotes: 1