Python char array declaration

Python char array declaration

You cant have a fixed size string. (Python doesnt work like that). But you can easily initialize a string to 100 characters:

myArray =  * 100

You can use array (an array in python have fixed type signature, but not fixed size):

>>> import array
myArray = array.array(c, [ for _ in xrange(100)])

>>> myArray
array(c, x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00)
>>> myArray[45]
x00

Notice that i initialize the default to couse in python you must initialize it with a value, and array have not fixed size (it is dynamic) but this will do.

Another option is to initialize the array and appende the values later, so instead of full of NULL (None in python) it will be just empty and grow at your will:

>>> a = array.array(c,)
>>> a
array(c)
>>> a.append(c)
>>> a
array(c, c)

Python char array declaration

Another way is to use numpy.chararray:

import numpy as np
myArray=np.chararray(100)
myArray[:]=0  #NULL is just a zero value

Results:

>>> myArray
chararray([b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0,
           b0, b0, b0, b0, b0, b0, b0, b0, b0, b0],
          dtype=|S1)

Leave a Reply

Your email address will not be published. Required fields are marked *