Character array in python 3?

In Python 2.7, I can create an array of these characters:

#Python 2.7 - works as expected
from array import array
x = array('c', 'test')

But in Python 3 'c' , typecode is no longer available. If I need an array of characters, what should I do? The type is also deleted 'u'.

#Python 3 - raises an error
from array import array
x = array('c', 'test')

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

+4
source share
2 answers

Use the byte array of 'b', encoded in a string and from a unicode string.

Convert to and from 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'
+3
source

, python , bytes interface bytearray. @MarkPerryman , .encode() .decode() :

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())
+2

All Articles