I searched around but i couldn't find any post to help me fix this problem, I found similar but i couldn't find any thing addressing this alone anyway.
Here's the the problem I have, I'm trying to have a python script search a text file, the text file has numbers in a list and every number corresponds to a line of text and if the raw_input match's the exact number in the text file it prints that whole line of text. so far It prints any line containing the the number.
Example of the problem, User types 20
then the output is every thing containing a 2
and a 0
, so i get 220 foo
200 bar
etc. How can i fix this so it just find "20"
here is the code i have
num = raw_input ("Type Number : ")
search = open("file.txt")
for line in search:
if num in line:
print line
Thanks.
Build lists of matched lines - several flavors:
Build generator of matched lines (memory efficient):
Print all matching lines (find all matches first, then print them):
Print all matching lines (print them lazily, as we find them)
Generators (produced by yield) are your friends, especially with large files that don't fit into memory.
To check for an exact match you would use
num == line
. Butline
has an end-of-line character\n
or\r\n
which will not be innum
sinceraw_input
strips the trailing newline. So it may be convenient to remove all whitespace at the end ofline
withyou should use regular expressions to find all you need:
regular expression will return you all numbers in a line as a list, for example:
so you don't match '200' or '220' for '20'.
It's very easy:
The check has to be like this:
If file.txt has a layout like this:
We split up
"1 foo"
into['1', 'foo']
and just use the first item, which is the number.