是否有可能将字符串中的所有字符转换为其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
unicode \uABCD
转义序列将覆盖所有字符范围。您是否想要最短的转义序列? - samplebiasord(c) <= 255
的字符将会以 \xAB
的形式进行编码,即使是在 Unicode 字符串中也是如此。 - samplebias
print "".join("\\x"+c.encode('hex') for c in "ABCDE")
- John La Rooy