将字符转换为它们的python转义序列



是否可以取一个字符串,并将所有字符转换为它们的Python转义序列?

repr()转义所有需要转义的字符

repr(string)

标准库中还有其他方法用于转义uri等

支持strunicode的完全转义(现在产生最短的转义序列):

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'u2018u2019hello thereu201cu201d', 'hello there'):
    esc = escape(text)
    print esc
    # code below is to verify by round-tripping
    import ast
    assert text == ast.literal_eval('u"' + esc + '"')
输出:

u2018u2019x68x65x6cx6cx6fx20x74x68x65x72x65u201cu201d
x68x65x6cx6cx6fx20x74x68x65x72x65

最新更新