title: Using Python to substitute or swap substrings in a file
body: <p>Suppose I have a line in an ASCII file of the following form:</p>
  
  <pre><code>{text1} {stringA} {text2} {stringB} {text3}
  </code></pre>
  
  <p>where <code>{stringA}</code> and <code>{stringB}</code> are substrings of interest.  Let's call them "A" and "B" respectively.  The strings <code>{text1}</code>, <code>{text2}</code>, and <code>{text3}</code> are strings of any length (possibly empty) that do not contain either A or B.</p>
  
  <p>What I want to do in Python is simply swap A and B such that the line goes from</p>
  
  <pre><code>{text1} {stringA} {text2} {stringB} {text3}
  </code></pre>
  
  <p>to</p>
  
  <pre><code>{text1} {stringB} {text2} {stringA} {text3}
  </code></pre>
  
  <p>I'd appreciate any help here.  I think that by getting help on this question, it will help me learn to better work with regular expressions in Python.</p>
  
  <p><strong>Note that <code>{text1}</code>, <code>{text2}</code>, and <code>{text3}</code> are unknown strings.</strong></p>
  
  <p>We know exactly the substrings A and B.  We know that A precedes B in the line.  However, we don't know what (if anything) is before/between/after them.</p>
  
  <p><strong>Examples (A=John, B=Tim):</strong></p>
  
  <p>(1) This:</p>
  
  <p>"I told John to give the bag to Tim."</p>
  
  <p>is changed to this:</p>
  
  <p>"I told Tim to give the bag to John."</p>
  
  <p>(2) This:</p>
  
  <p>"John said hello to Tim."</p>
  
  <p>is changed to this:</p>
  
  <p>"Tim said hello to John."</p>
  
  <p>(3) This:</p>
  
  <p>"John!h9aghagTim"</p>
  
  <p>is changed to this:</p>
  
  <p>"Tim!h9aghagJohn"</p>