且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python 3中将utf-8 Unicode序列转换为utf-8字符

更新时间:2022-01-25 07:19:29

我相信编解码器模块提供了此实用程序:

I believe that the codecs module provides this utility:

>>> import codecs
>>> codecs.decode("1+1\\u003d2", encoding='unicode_escape')
'1+1=2'

这可能是一个更大的问题。这些字符串如何排在首位?

This probably points to a larger problem, though. How do these strings come to be in the first place?

注意,如果这是从有效的JSON字符串中提取的(在这种情况下,它将丢失引号) ,您可以简单地使用:

Note, if this is being extracted from a valid JSON string (in this case it would be missing the quotes), you could simply use:

>>> import json
>>> json.loads('"1+1\\u003d2"')
'1+1=2'