![](/img/trans.png)
[英]How do convert unicode escape sequences to unicode characters in a python string
[英]Converting characters to their python escape sequences
是否可以獲取字符串,並將所有字符轉換為Python轉義序列?
repr()
轉義所有需要轉義的字符
repr(string)
標准庫中還有其他方法可用於轉義URI等
支持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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.