python array.tostring() 中有 NUL 字节

标签 python arrays unicode python-3.x

我在单元测试测试用例中有以下代码(作为示例)

def test(self):
    a = array('u','\0'*3)
    a[0] = 'h'
    a[1] = 'h'
    a[2] = 'h'

    self.assertEqual(a.tostring(), "hhh")

断言失败并出现以下错误:

AssertionError: b'h\x00\x00\x00h\x00\x00\x00h\x00\x00\x00' != 'hhh'

现在我明白我创建的数组是 Unicode 字符的,长度为 4 个字节,因此我输入的每个字符都有额外的 3 个 NUL 字节。我的问题是:

  1. 我可以将字符串“hhh”转换为断言内联的 Unicode 表示形式吗?
  2. 是否有用于创建数组的 ascii 选项?

编辑:回答出现的问题: 1.我使用的是Python 3 2. array 来自模块 array,可以通过以下方式导入: from array import array

最佳答案

我想您正在使用 Python3,它似乎缺少 array'c' 选项。

在这种情况下,我会这样做

a = array.array("b",4*(0,))
a[0] = 'h'
a[1] = 'h'
a[2] = 'h'

另一种选择是

a=array.array('u', "hhh") # the same as yours, but shorter
a.tounicode()

但是你有一个 unicode 字符串而不是 bytes() 对象。

关于python array.tostring() 中有 NUL 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377165/

相关文章:

python - Pandas 的移动平均线

python - 使用两个张量向量创建 N x M 张量矩阵并为每个 (n,m) 对应用一个函数

c - C中动态分配的二维( double )数组

python - 添加两个大小不等的 numpy 数组(长度 n 和 m)以生成 n * m 数组而不使用 for 循环

Python mysql 连接器 LIKE 针对 unicode 值

python - 如何通过网络发送对象

python - 我如何分析由多个模块和类组成的 python 脚本?

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 如何设置整理器强度和分解以按首字母对 unicode 字符串进行排序

python - 如何让 PyC​​harm 在其控制台中显示 unicode 数据?