String replace with re sub matching the exact string
<p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p>

<p>My code :</p>

<pre><code>input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print input_file
</code></pre>

<p>So, I'm expecting result like this :</p>

<pre><code>bar afooa
</code></pre>

<p>Thanks in advance</p>

<p>From the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">doc</a>, you can set <code>count = 1</code> of <code>re.sub()</code>to just change the first occurrence of the pattern. Also, remove the <code>^</code> and <code>$</code> since you donot want to search for the whole line containing only the word <code>foo</code>. Sample code:</p>

<pre><code>import re; 
input_file = "foo afooa"; 
input_file = re.sub(r'foo', 'bar', input_file, count = 1); 
print input_file;
</code></pre>

python regex