<p>您已经提到,您正在使用变量<code>s</code>来存储字符串,而不是在其中使用<code>r</code>前缀。所以有一个问题。如果字符串中有<code>\u</code>或<code>\x</code>或<code>\U</code>或<code>\N</code>,则将引发<code>SyntaxError</code>。
例如:</p>
<pre><code>>>> s = 'There is no way o\ut'
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 17-18: truncated \uXXXX escape
>>> s = 'Cross symbol(\x) says it is wrong'
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 13-14: truncated \xXX escape
>>> s = 'What an escape Seque\Nce'
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 20-21: malformed \N character escape
>>> s = 'What an escape Seq\Uence'
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 18-20: truncated \UXXXXXXXX escape
</code></pre>
<p>因此,如果我假设您的字符串没有<code>\u</code>或<code>\x</code>或<code>\U</code>或<code>\N</code>,那么您可以尝试以下方法:</p>
<pre><code>>>> import re
>>> def repEsc(s):
s = re.sub('\a', r'\\a', s)
s = re.sub('\b', r'\\b', s)
s = re.sub('\f', r'\\f', s)
s = re.sub('\v', r'\\v', s)
s = re.sub('\n', r'\\n', s)
s = re.sub('\r', r'\\r', s)
s = re.sub('\t', r'\\t', s)
return s
>>> s = '\triangle \bold \new \regex'
>>> s = repEsc(s)
>>> s
'\\triangle \\bold \\new \\regex'
>>> print(s)
\triangle \bold \new \regex
</code></pre>