将字符转换为Python转义序列
有没有办法把一个字符串里的所有字符都转换成它们在Python中的转义序列?
2 个回答
5
repr()
函数会把所有需要转义的字符都处理成可以安全显示的形式。
repr(string)
在标准库中,还有其他方法可以用来处理像URI这样的转义问题。
3
支持对 str
和 unicode
的完全转义(现在会生成最短的转义序列):
def escape(s):
ch = (ord(c) for c in s)
return ''.join(('\\x%02x' % c) if c <= 255 else ('\\u%04x' % c) for c in ch)
for text in (u'\u2018\u2019hello there\u201c\u201d', 'hello there'):
esc = escape(text)
print esc
# code below is to verify by round-tripping
import ast
assert text == ast.literal_eval('u"' + esc + '"')
输出结果:
\u2018\u2019\x68\x65\x6c\x6c\x6f\x20\x74\x68\x65\x72\x65\u201c\u201d
\x68\x65\x6c\x6c\x6f\x20\x74\x68\x65\x72\x65