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')
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: cannot use a str to initialize an array with typecode 'c'
解决方案
Use an array of bytes 'b', with encoding to and from a unicode string.
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'