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>Your code does work and can be combined to a single expression:</p>

<pre><code>&gt;&gt;&gt; print("abc-ccd_2013".replace("-","\-").replace("_","\_"))
abc\-ccd\_2013
</code></pre>

<p>Note the difference of <code>print</code> vs <code>repr</code>:</p>

<pre><code>&gt;&gt;&gt; "abc-ccd_2013".replace("-","\-").replace("_","\_")
'abc\\-ccd\\_2013'
</code></pre>

<p>Is equivalent to:</p>

<pre><code>&gt;&gt;&gt; print(repr("abc-ccd_2013".replace("-","\-").replace("_","\_")))
'abc\\-ccd\\_2013'
</code></pre>

python console