在某些时候,我们的python脚本接收串那样:使用不正确格式化字符串Python的问题包含 X
In [1]: ab = 'asd\xeffe\ctive'
In [2]: print ab
asd�fe\ctve \ \\ \\\k\\\
数据被破坏,我们需要逃避\ x到正确解释为\ X,但\ c具有因此字符串中没有特殊含义,因此必须完好无损。
到目前为止,我发现的最接近的解决办法是做这样的事情:从IPython中采取
In [1]: ab = 'asd\xeffe\ctve \\ \\\\ \\\\\\k\\\\\\'
In [2]: print ab.encode('string-escape').replace('\\\\', '\\').replace("\\'", "'")
asd\xeffe\ctve \ \\ \\\k\\\
输出,我假设AB是一个字符串不是unicode字符串(在后一种情况下,我们将不得不做一些像即:
def escape_string(s):
if isinstance(s, str):
s = s.encode('string-escape').replace('\\\\', '\\').replace("\\'", "'")
elif isinstance(s, unicode):
s = s.encode('unicode-escape').replace('\\\\', '\\').replace("\\'", "'")
return s
一个黑客是使用'repr',即'repr(s)[1:-1]'。 – DSM
不直接调用'__repr__'。它拼写为'repr(ab)'。 – habnabit
在字符串数据的源头修复这个问题更有意义。你能详细说明为什么你首先以ab ='asd \ xeffe \ ctive''的形式接收数据(而不是正确清理'ab ='asd \\ xeffe \\ ctive'')? – ezod