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>Instead of ^ and $ , use \b to match boundary.</p>

<pre><code>&gt;&gt;&gt; a="foo afooa"
&gt;&gt;&gt; b= re.sub(r"\bfoo\b",'bar',a)
&gt;&gt;&gt; b
'bar afooa'
&gt;&gt;&gt;
</code></pre>

python regex