Array of characters in python 3?
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'
It seems that the python devs are not longer supporting storing strings in arrays since most of the use cases would use the new bytes
interface or bytearray
. @MarkPerryman's solution seems to be your best bet although you could make the .encode()
and .decode()
transparent with a subclass:
from array import array
class StringArray(array):
def __new__(cls,code,start=''):
if code != "b":
raise TypeError("StringArray must use 'b' typecode")
if isinstance(start,str):
start = start.encode()
return array.__new__(cls,code, start)
def fromstring(self,s):
return self.frombytes(s.encode())
def tostring(self):
return self.tobytes().decode()
x = StringArray('b','test')
print(x.tostring())
x.fromstring("again")
print(x.tostring())