Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of characters in python 3?

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'

like image 766
C_Z_ Avatar asked May 10 '16 15:05

C_Z_


People also ask

What is an array of characters in Python?

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Does Python 3 have arrays?

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

Is [] a list or array in Python?

What Is an Array in Python? An array is also a data structure that stores a collection of items. Like lists, arrays are ordered, mutable, enclosed in square brackets, and able to store non-unique items.


2 Answers

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'
like image 146
Mark Perryman Avatar answered Sep 27 '22 20:09

Mark Perryman


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())
like image 23
Tadhg McDonald-Jensen Avatar answered Sep 27 '22 19:09

Tadhg McDonald-Jensen