Reputation: 1194
Im trying to search and find a correct word in a file
file = ('data.bin', '+r')
Filefind = file.read()
f = raw_input("search a word: ")
While f in Filefind:
print "this word is found!"
This code actually find the word I have entered, but it find the word even if it's not fully entered For example, if I have "findme" word in the file, script will find it if I enter only "fi" in raw_input
How to write a script that returns me True, if it finds the full word in a file?
Upvotes: 1
Views: 615
Reputation: 251146
Use regex
with word boundaries:
import re
def search(word, text):
return bool(re.search(r'\b{}\b'.format(re.escape(word)), text))
...
>>> search("foo", "foobar foospam")
False
>>> search("foo", "foobar foo")
True
Upvotes: 4