python 3中的字符数组?

C_Z*_*_Z_ 5 python arrays python-3.x

Python 2.7中,我可以像这样创建一个字符数组:

#Python 2.7 - works as expected
from array import array
x = array('c', 'test')
Run Code Online (Sandbox Code Playgroud)

但是在Python 3 'c'中不再是一个可用的类型代码.如果我想要一个字符数组,我该怎么办?该'u'类型也被删除.

#Python 3 - raises an error
from array import array
x = array('c', 'test')
Run Code Online (Sandbox Code Playgroud)

TypeError:不能使用str来初始化类型为'c'的数组

Mar*_*man 5

使用字节数组“ b”,并与一个Unicode字符串进行编码。

使用array.tobytes().decode()和在字符串之间来回转换array.frombytes(str.encode())

>>> x = array('b')
>>> x.frombytes('test'.encode())
>>> x
array('b', [116, 101, 115, 116])
>>> x.tobytes()
b'test'
>>> x.tobytes().decode()
'test'
Run Code Online (Sandbox Code Playgroud)