Python中将\\uxxxx转换为Unicode字符串的方法

半杯拿铁
半杯拿铁
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍Python中将形如\\uXXXX的字符串转换为实际中文的方法。针对re库替换报错问题,推荐使用json.loads处理JSON格式字符串;针对Python3中str无decode属性,提供encode('utf-8').decode('unicode_escape')的正确写法,解决编码转换难题。

今天遇到一个实用的技术问题,需要将普通的Unicode字符串转换为包含Unicode编码字符的字符串,具体示例如下:

目标是将字符串 \\u9500\\u552e 转换为对应的中文文本 \u9500\u552e,即“销售”。

直观上似乎可以通过正则表达式库 re 去除前缀反斜杠来实现,但在执行替换操作时会触发如下错误:

Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> re.sub(r"(\)\u", r'', t) File "D:\Python36\lib\re.py", line 191, in sub return _compile(pattern, flags).sub(repl, string, count) File "D:\Python36\lib\re.py", line 301, in _compile p = sre_compile.compile(pattern, flags) File "D:\Python36\lib\sre_compile.py", line 562, in compile p = sre_parse.parse(p, flags) File "D:\Python36\lib\sre_parse.py", line 855, in parse p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0) File "D:\Python36\lib\sre_parse.py", line 416, in _parse_sub not nested and not items)) File "D:\Python36\lib\sre_parse.py", line 765, in _parse p = _parse_sub(source, state, sub_verbose, nested + 1) File "D:\Python36\lib\sre_parse.py", line 416, in _parse_sub not nested and not items)) File "D:\Python36\lib\sre_parse.py", line 502, in _parse code = _escape(source, this, state) File "D:\Python36\lib\sre_parse.py", line 362, in _escape raise source.error("incomplete escape %s" % escape, len(escape)) sre_constants.error: incomplete escape \u at position 3

错误提示表明,去除前缀反斜杠后剩余的 \u 序列无法构成完整的转义字符。

此时问题看似棘手,但我们不应轻易放弃。

通过搜索引擎查找相关案例,发现已有成熟的解决方案,且方法十分巧妙。

实际上,可以利用 json 库的 loads 方法来实现这一转换。

具体解决代码如下:

import json
s = '\\u9500\\u552e'
print(json.loads(f'"{s}"'))

补充说明:在Python3中将字符串Unicode编码转换为中文显示。

记录一个常见的开发场景:

当获取的文本以“\uxxxx”格式字符串呈现时,若在Python3中直接调用 text.decode('unicode_escape') 会报错,提示 ‘str' object has no attribute 'decode'。

正确的处理方式是:

text.encode('utf-8').decode("unicode_escape")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表