gpt4 book ai didi

python - python 3中的字符数组?

转载 作者:太空狗 更新时间:2023-10-30 00:54:33 25 4
gpt4 key购买 nike

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')

TypeError: cannot use a str to initialize an array with typecode 'c'

最佳答案

使用字节数组“b”,编码为 un​​icode 字符串。

使用 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'

关于python - python 3中的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com