2011-05-03 81 views

回答

3

同時支持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'\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 
+0

那些包含unicode字符和標準字符混合的字符串呢? – Acorn 2011-05-03 02:50:11

+0

@Acorn'unicode \ uABCD'轉義序列將覆蓋全部字符。你想要最短的逃生次序嗎? – samplebias 2011-05-03 02:56:27

+0

啊,當然,我被笨.. – Acorn 2011-05-03 02:58:03

5

repr()逃脫需要進行轉義的所有字符

repr(string) 

有標準庫中的其他方法逃避URI的喜好等

+0

有沒有辦法逃避的所有字符? – Acorn 2011-05-03 02:04:09

+0

@Acorn,你可以做這樣的事情'打印 「」。加入( 「\\ X」 + c.encode( '十六進制')對C中的 「ABCDE」)' – 2011-05-03 02:12:03

+0

這不會爲Unicode字符的工作。 – Acorn 2011-05-03 02:12:48