擅长:python、mysql、java
<p>只需使用<code>'string_escape'</code>编解码器对其进行编码。</p>
<pre><code>>>> print "foo\nbar".encode('string_escape')
foo\nbar
</code></pre>
<p>在Python3中,<code>'string_escape'</code>变成了<code>unicode_escape</code>。另外,我们需要对bytes/unicode更加小心一些,这样就需要在编码之后进行解码:</p>
<pre><code>>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))
</code></pre>
<p><a href="https://docs.python.org/3/library/codecs.html#text-encodings" rel="noreferrer">unicode_escape reference</a></p>