python3:Unescape unicode转义被未转义字符包围
我收到了python3:Unescape unicode转义被未转义字符包围,python,python-3.x,unicode,escaping,unicode-escapes,Python,Python 3.x,Unicode,Escaping,Unicode Escapes,我收到了json数据,其中一些unicode字符已转义,而另一些则未转义 >>> example = r'сло\u0301во' 什么是取消这些角色的最佳方式?在下面的示例中,函数unescape是什么样子的?是否有一个内置函数可以实现这一点 >>> unescape(example) сло́во 此解决方案假定原始字符串中\u的每个实例都是unicode转义: def unescape(in_str): """Unicode-unescape
json
数据,其中一些unicode字符已转义,而另一些则未转义
>>> example = r'сло\u0301во'
什么是取消这些角色的最佳方式?在下面的示例中,函数unescape
是什么样子的?是否有一个内置函数可以实现这一点
>>> unescape(example)
сло́во
此解决方案假定原始字符串中
\u
的每个实例都是unicode转义:
def unescape(in_str):
"""Unicode-unescape string with only some characters escaped."""
in_str = in_str.encode('unicode-escape') # bytes with all chars escaped (the original escapes have the backslash escaped)
in_str = in_str.replace(b'\\\\u', b'\\u') # unescape the \
in_str = in_str.decode('unicode-escape') # unescape unicode
return in_str
…或者在一行中
def unescape(in_str):
"""Unicode-unescape string with only some characters escaped."""
return in_str.encode('unicode-escape').replace(b'\\\\u', b'\\u').decode('unicode-escape')
这很奇怪,如果您键入
r'Саö\u0301аа'
,python解释器将把转义转换为相应的字符,字符串实际上将包含Сааа
。它可能会以不同的方式将其打印到控制台,具体取决于您的代码页。