7
votes

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'

3
Warning: this basically asks how to store characters and then accepts an answer which stores encoded characters as a byte array. In case you didn't notice, that's not really an array of characters. Basically it means that the person didn't get it: use a string. - Maarten Bodewes

3 Answers

9
votes

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'
4
votes

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())
-1
votes

Addition to the answer of Mark Perryman:

>> x.frombytes('hellow world'.encode())
>>> x
array('b', [116, 101, 115, 116, 104, 101, 108, 108, 111, 119, 32, 119, 111, 114, 108, 100])
>>> x.tostring()
b'testhellow world'
>>> x[1]
101
>>> x[1]^=0x1
>>> x[1]
100

>> x.tobytes().decode()
'wdsthellow world'
>>> x.tobytes
<built-in method tobytes of array.array object at 0x11330b7b0>
>>> x.tobytes()
b'wdsthellow world'

Exactly, I need to convert a special byte from my array list recently, have tried various methods, then get the new simple method:x[1]^=0x1, and could get a array easily via array.array['b', <my bytes list>]