python 3中的字符数组? [英] Array of characters in python 3?
本文介绍了python 3中的字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 2.7 中,我可以创建一个字符数组,如下所示:
In Python 2.7 I can create an array of characters like so:
#Python 2.7 - works as expected
from array import array
x = array('c', 'test')
但是在'c'
不再是可用的类型代码.如果我想要一个字符数组,该怎么办? 'u'
类型也将被删除.
But in Python 3 'c'
is no longer an available typecode. If I want an array of characters, what should I do? The 'u'
type is being removed as well.
#Python 3 - raises an error
from array import array
x = array('c', 'test')
TypeError:无法使用str初始化类型代码为'c'的数组
TypeError: cannot use a str to initialize an array with typecode 'c'
推荐答案
使用字节'b'的数组,并在Unicode字符串之间进行编码.
Use an array of bytes 'b', with encoding to and from a unicode string.
使用array.tobytes().decode()
和array.frombytes(str.encode())
在字符串之间进行转换.
Convert to and from a string using array.tobytes().decode()
and 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 3中的字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文