Suppose I have a text file where each line contains either ‘1’ or ‘-1.’ How do I search through the file to check if the file contains at least one ‘1’?
Initially, I had the following.
if re.search(r'\b1', f.read()): return true
else: return false
However, this does not work because ‘-‘ is not considered an alphanumeric string and returns true if the file does not contain a single ‘1.’ What is the best way to determine if the file contains ‘1’?
Using the
re.MULTILINEflag,^will match start of lines (instead of only start of subject):This will match if any line starts with
1.See http://docs.python.org/library/re.html#regular-expression-syntax
This alternative solution avoid reading the file entirely: