将字节字符串转换为Unicode字符串

39

我有如下代码:

a = "\u0432"
b = u"\u0432"
c = b"\u0432"
d = c.decode('utf8')

print(type(a), a)
print(type(b), b)
print(type(c), c)
print(type(d), d)

输出结果为:

<class 'str'> в
<class 'str'> в
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432
为什么在后一种情况下我看到的是字符代码,而不是字符本身?我该如何将字节字符串转换为Unicode字符串,以便在输出时看到字符而不是代码?
2个回答

64
在Python中的字符串(或Unicode对象),\u具有特殊的含义,表示“这里是一个Unicode字符,其Unicode ID由此指定”。因此,u"\u0432"将得到字符в。
前缀b''告诉你这是一系列8位字节,字节对象没有Unicode字符,因此\u代码没有特殊含义。因此,b"\u0432"只是字节序列\\, u, 0, 4, 32
本质上,你有一个包含Unicode字符规范而不是Unicode字符的8位字符串。
您可以使用unicode转义编码器来转换此规范。
>>> c.decode('unicode_escape')
'в'

1
在使用Redis集合并尝试将其转换为JSON时,我遇到了这个问题。Redis返回一组字节数据。使用unicode_escape完美解决了这个问题。 - lukik

1
我喜欢Lennart的回答,它让我朝着解决我所面临的特定问题的正确方向前进。我添加的是能够生成字符串中 \u???? 规范的兼容html代码的能力。基本上,只需要一行代码:
results = results.replace('\\u','&#x')

这一切都源于将JSON结果转换为在浏览器中显示良好的需求。以下是与云应用程序集成的一些测试代码:
# References:
# https://dev59.com/wGkw5IYBdhLWcg3woMJD
# https://docs.python.org/3/library/http.client.html
# http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
# https://dev59.com/OXRB5IYBdhLWcg3wgHWr
# http://www.w3schools.com/charsets/ref_utf_punctuation.asp
# https://dev59.com/xGYr5IYBdhLWcg3wOX66

import urllib.request
import json

body = [ { "query": "co-development and language.name:English", "page": 1, "pageSize": 100 } ]
myurl = "https://core.ac.uk:443/api-v2/articles/search?metadata=true&fulltext=false&citations=false&similar=false&duplicate=false&urls=true&extractedUrls=false&faithfulMetadata=false&apiKey=SZYoqzk0Vx5QiEATgBPw1b842uypeXUv"
req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondatabytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondatabytes))
print ('\n', jsondatabytes, '\n')
response = urllib.request.urlopen(req, jsondatabytes)
results = response.read()
results = results.decode('utf-8')
results = results.replace('\\u','&#x') # produces html hex version of \u???? unicode characters
print(results)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接