将字符转换为其python转义序列 [英] Converting characters to their python escape sequences
本文介绍了将字符转换为其python转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以采用字符串并将所有个字符转换为它们的Python转义序列?
Is it possible to take a string, and convert all the characters into their Python escape sequences?
推荐答案
同时支持 str
和 unicode
的全转义(现在产生最短的转义序列):
Supports full escaping of both str
and unicode
(now produces the shortest escape sequence):
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
这篇关于将字符转换为其python转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文