Python 字符数组声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34675555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python char array declaration
提问by wahab
Is there a way to declare a char array of a fixed size in python as in C for examplechar myArray[100]
I also want to initializa all the characters with NULL.
有没有办法在python中声明一个固定大小的char数组,例如在C中char myArray[100]
我也想用NULL初始化所有字符。
采纳答案by Martin Bonner supports Monica
You can't have a fixedsize string. (Python doesn't work like that). But you can easily initialize a string to 100 characters:
你不能有固定大小的字符串。(Python 不是那样工作的)。但是您可以轻松地将字符串初始化为 100 个字符:
myArray = ">>> import array
myArray = array.array('c', ['>>> a = array.array('c',)
>>> a
array('c')
>>> a.append('c')
>>> a
array('c', 'c')
' 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'
" * 100
回答by Netwave
You can use array(an array in python have fixed type signature, but not fixed size):
您可以使用数组(python 中的数组具有固定类型签名,但不固定大小):
import numpy as np
myArray=np.chararray(100)
myArray[:]=0 #NULL is just a zero value
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.
请注意,我在 python 中将默认值初始化为 '\0' 你必须用一个值初始化它,并且数组没有固定大小(它是动态的),但这可以。
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:
另一种选择是初始化数组并稍后附加值,因此它不会充满 NULL(python 中的 None),而是空的并随您的意愿增长:
>>> myArray
chararray([b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0',
b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0'],
dtype='|S1')