title: Python: Replace a string as variable in a file
body: <p>If I have a file contents like this:</p>
  
  <pre><code>old_string
  -old_string
  </code></pre>
  
  <p>I want to change only "old_string" to be "+new_string" so the result looks like</p>
  
  <pre><code>+new_string
  -old_string
  </code></pre>
  
  <p>my code gives this result: </p>
  
  <pre><code>+new_string
  -+new_string
  </code></pre>
  
  <p>This is my code :</p>
  
  <pre><code>    with open(filename) as f:
  
      s = f.read()
  
      if old_string not in s:
  
          return False
  
  with open(filename, 'w') as f:
  
      s = s.replace(old_string, new_string)
  
      f.write(s)
  
      return True
  </code></pre>
  
  <p>i Tried regex, but it won't work since I pass the regex as a variables, this is what I did so far:</p>
  
  <pre><code>    with open (filename, 'r' ) as f:
  
         content = f.read()
  
  content_new = re.sub('(\%old_string)', r'\new_string'%(old_string,new_string), content, flags = re.M)      
  </code></pre>