How to change a string into a formatted string?
<p>I want to change a source string: </p>

<pre><code>str1 = 'abc-ccd_2013'
</code></pre>

<p>into the following target string:</p>

<pre><code>str2 = 'abc\-ccd\_2013'.
</code></pre>

<p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p>

<p>The following method is not working:</p>

<pre><code>    &gt;&gt;&gt; str1
    'abc-ccd_2013'
    &gt;&gt;&gt; a1 = str1.replace("-","\\-")
    &gt;&gt;&gt; a1
    'abc\\-ccd_2013'
    &gt;&gt;&gt; a1 = str1.replace("-","\-")
    &gt;&gt;&gt; a1
    'abc\\-ccd_2013'
    &gt;&gt;&gt; a1 = str1.replace('-','\-')
    &gt;&gt;&gt; a1
    'abc\\-ccd_2013'
    &gt;&gt;&gt; a1 = str1.replace(r'-',r'\-')
    &gt;&gt;&gt; a1
    'abc\\-ccd_2013'
    &gt;&gt;&gt; 
</code></pre>

<p>This works. When printing raw string, '\' is replaced with '\\' so it does not interpret it as escape character used for e.g. endline character '\n', tab character '\t' and so on.
Try command
<code>print str2</code> or <code>print a1</code>
and it will be fine.</p>

<p>Update: Even stackoverflow replaces '\\' with '\', so instead I have to type '\\\' (to type this I had to use 5 slashes) :D</p>

python console