这是一个只转义unicode字符串中的控制字符的解决方案。
control_chars = [unichr(c) for c in range(0x20)] # you may extend this as required
def control_escape2(s):
return u''.join([c.encode('unicode_escape') if c in control_chars else c for c in s])
Which is the correct way to encode escape characters in Python 2 without killing Unicode?
这听起来是一个功能,可能值得放置一个模块,以便我不必总是复制相同的代码。在现有的python模块中有这样的东西吗?
是和否:根据this answer,unicodedata
模块具有与此相关的实用程序,但它本身没有escape_control_characters()
函数。