Your regex is currently r'^foo$'
which basically matches the string 'foo' only.
If you just changed it to r'^foo'
it will match as long as 'foo' is found at the start of the string, but unlike your previous pattern it doesn't care about what follows foo.
Here is an example:
input_file = "foo afooa"
input_file = re.sub(r'^foo', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo', 'bar', input_file2)
print input_file
print input_file2
output:
bar afooa
barb afooa
Now if you don't want to match a part of a string, but match the whole string 'foo' at the start of the line, then you need to add a boundary '\b' match like shown below:
input_file = "foo afooa"
input_file = re.sub(r'^foo\b', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo\b', 'bar', input_file2)
print input_file
print input_file2
output:
bar afooa
foob afooa
Or if you want to just replace the first occurrence of the full word 'foo', then use the pattern suggested by @DineshPundkar and limit the number of substitutions to 1 like @Tuan333 just mentioned.
So, in this case your code will look like:
input_file = "a foo afooa foo bazfooz"
input_file = re.sub(r'\bfoo\b', 'bar', input_file, 1)
print input_file
output:
a bar afooa foo bazfooz