转换unicode字符串中的字节字符串

2024-09-29 18:48:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个密码:

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字符串,以便在输出时看到字符而不是其代码?


Tags: 字符串代码密码字节bytestypeunicode情况
2条回答

喜欢伦纳特的回答。它使我走上了解决我所面临的特殊问题的正确道路。我添加的是能够为您生成与html兼容的代码????字符串中的规范。基本上,只需要一行:

results = results.replace('\\u','&#x')

这一切都是因为需要将JSON结果转换为在浏览器中显示良好的结果。下面是一些与云应用程序集成的测试代码:

# References:
# http://stackoverflow.com/questions/9746303/how-do-i-send-a-post-request-as-a-json
# https://docs.python.org/3/library/http.client.html
# http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
# http://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string
# http://www.w3schools.com/charsets/ref_utf_punctuation.asp
# http://stackoverflow.com/questions/13837848/converting-byte-string-in-unicode-string

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)

在字符串(或Python 2中的Unicode对象)中,\u有一个特殊的含义,即“这里有一个由它的Unicode ID指定的Unicode字符”。因此u"\u0432"将产生字符b。

前缀b''告诉您这是一个8位字节的序列,bytes对象没有Unicode字符,因此\u代码没有特殊含义。因此,b"\u0432"只是字节\u0432的序列。

实际上,8位字符串不包含Unicode字符,而是包含Unicode字符的规范。

可以使用unicode转义编码器转换此规范。

>>> c.decode('unicode_escape')
'в'

相关问题 更多 >

    热门问题