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>You could also do the following : </p>

<pre><code>str1 = 'abc-ccd_2013'
repl = ('-', '\-'), ('_', '\_')
print reduce(lambda a1, a2: a1.replace(*a2), repl, str1)
</code></pre>

<p>You will have to use the print function to get your desired result.</p>

python console