Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python char array declaration [duplicate]

Is there a way to declare a char array of a fixed size in python as in C for example
char myArray[100]
I also want to initializa all the characters with NULL.

like image 907
wahab Avatar asked Mar 08 '26 09:03

wahab


2 Answers

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

myArray = "\0" * 100
like image 50
Martin Bonner supports Monica Avatar answered Mar 10 '26 23:03

Martin Bonner supports Monica


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

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

>>> myArray
array('c', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> myArray[45]
'\x00'

Notice that i initialize the default to '\0' 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')
like image 34
Netwave Avatar answered Mar 10 '26 22:03

Netwave