title: Python replace forward slash with back slash
body: <p>I have</p>
  
  <pre><code>foo = '/DIR/abc'
  </code></pre>
  
  <p>and I want to convert it to</p>
  
  <pre><code>bar = '\\MYDIR\data\abc'
  </code></pre>
  
  <p>So, here's what I do in Python:</p>
  
  <pre><code>&gt;&gt;&gt; foo = '/DIR/abc'
  &gt;&gt;&gt; bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
    File "&lt;stdin&gt;", line 1
      bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
                                                   ^
  SyntaxError: EOL while scanning string literal
  </code></pre>
  
  <p>If, however, I try to escape the last backslash by entering instead <code>bar = foo.replace(r'/DIR/',r'\\MYDIR\data\\')</code>, then I get this monstrosity:</p>
  
  <pre><code>&gt;&gt;&gt; bar2
  '\\\\MYDIR\\data\\\\abc'
  </code></pre>
  
  <p>Help! This is driving me insane.</p>