【发布时间】:2012-10-11 16:07:27
【问题描述】:
在某些时候,我们的 python 脚本会收到这样的字符串:
In [1]: ab = 'asd\xeffe\ctive'
In [2]: print ab
asd�fe\ctve \ \\ \\\k\\\
数据已损坏,我们需要转义 \x 才能正确解释为 \x,但 \c 在字符串中没有特殊含义,因此必须完好无损。
到目前为止,我找到的最接近的解决方案是:
In [1]: ab = 'asd\xeffe\ctve \\ \\\\ \\\\\\k\\\\\\'
In [2]: print ab.encode('string-escape').replace('\\\\', '\\').replace("\\'", "'")
asd\xeffe\ctve \ \\ \\\k\\\
来自 IPython 的输出,我假设 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
【问题讨论】:
-
一个(脆弱的!)hack 是使用
repr,即repr(s)[1:-1]。 -
不要直接打电话给
__repr__。拼写为repr(ab)。 -
在字符串数据的源头解决这个问题更有意义。您能否详细说明为什么您首先以
ab = 'asd\xeffe\ctive'的形式接收数据(而不是经过适当清理的ab = 'asd\\xeffe\\ctive')? -
如果我们知道损坏的数据是如何进入我们的系统的,我就不会问这个问题了,对吗? :) 我完全同意我们需要修复一个来源,但到目前为止来源是神秘的。我们无法重现用户正在做的任何事情。
-
@Drachenfels:您知道字符串转义将换行符转换为“\\n”(两个字符)以及所有其他有效的转义符吗?