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>Your regex is currently <code>r'^foo$'</code> which basically matches the string 'foo' <strong><em>only</em></strong>.</p>

<p>If you just changed it to <code>r'^foo'</code> 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.</p>

<p>Here is an example:</p>

<pre><code>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
</code></pre>

<p>output:</p>

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

<p>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:</p>

<pre><code>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
</code></pre>

<p>output:</p>

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

<p>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. </p>

<p>So, in this case your code will look like:</p>

<pre><code>input_file = "a foo afooa foo bazfooz"
input_file = re.sub(r'\bfoo\b', 'bar', input_file, 1)
print input_file
</code></pre>

<p>output:</p>

<pre><code>a bar afooa foo bazfooz
</code></pre>

python regex