我可以将Unicode字符串转储为字节数组吗?

5 投票
2 回答
5098 浏览
提问于 2025-04-17 09:37

我想把一个简单的Unicode字符串转换成字节数组,这样我就可以把每个字节当作整数来使用。这样做可以吗?

我想把字符串 u"Hello World" 转换成UTF-8格式,结果看起来像这样:

[0x01, 0x02, ..., 0x02]

我该怎么高效地做到这一点呢?

2 个回答

13

如果你在寻找Python中的bytearray

my_array = bytearray(u"hello, world", encoding="utf-8")
8

你的问题可能有两种意思:一种是把Unicode字符串用比如UTF8的方式编码,然后得到一串字节;另一种是得到Unicode的代码点列表。

如果是第一种情况:

list_of_bytes = map(ord, my_unicode_string.encode('utf8'))

如果是第二种情况:

list_of_code_points = map(ord, my_unicode_string)

撰写回答