How to match exact string/word while searching a list. I have tried, but its not correct. below I have given the sample list, my code and the test results
list = ['Hi, hello', 'hi mr 12345', 'welcome sir']
my code:
for str in list:
if s in str:
print str
test results:
s = "hello" ~ expected output: 'Hi, hello' ~ output I get: 'Hi, hello' s = "123" ~ expected output: *nothing* ~ output I get: 'hi mr 12345' s = "12345" ~ expected output: 'hi mr 12345' ~ output I get: 'hi mr 12345' s = "come" ~ expected output: *nothing* ~ output I get: 'welcome sir' s = "welcome" ~ expected output: 'welcome sir' ~ output I get: 'welcome sir' s = "welcome sir" ~ expected output: 'welcome sir' ~ output I get: 'welcome sir'
My list contains more than 200K strings
It looks like you need to perform this search not only once so I would recommend to convert your list into dictionary:
So now you can easily do:
p.s. probably you have to improve
item.split()to handle commas, point and other separators. maybe use regex and\w.p.p.s. as cularion mentioned this won’t match “welcome sir”. if you want to match whole string, it is just one additional line to proposed solution. but if you have to match part of string bounded by spaces and punctuation
regexshould be your choice.