在 Python 2.7 中,我可以像这样创建一个字符数组:
#Python 2.7 - works as expected
from array import array
x = array('c', 'test')
但在 Python 3 中 'c'
不再是可用的类型代码。如果我想要一个字符数组,我该怎么办? 'u'
类型也被删除。
#Python 3 - raises an error
from array import array
x = array('c', 'test')
类型错误:无法使用 str 来初始化类型代码为“c”的数组
原文由 CZ 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用字节数组“b”,编码为 unicode 字符串。
使用
array.tobytes().decode()
和array.frombytes(str.encode())
--- 与字符串相互转换。