2016-05-10 39 views
4

Python 2.7我可以像這樣創建一個字符數組:python 3中的字符數組?

#Python 2.7 - works as expected 
from array import array 
x = array('c', 'test') 

Python 3'c'不再可用的類型代碼。如果我想要一系列角色,我該怎麼做? 'u'類型也正在被刪除。

#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'

+0

無論你的代碼示例是相同的。 –

+2

@DawidFerenczy是的。一個是Python 2.7,一個是Python 3.4。 –

回答

3

使用的字節 'B' 的陣列,用編碼向和從一個unicode字符串。

使用array.tobytes().decode()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' 
+0

謝謝,這個作品完美 –

2

看來,蟒蛇開發者都不再支持存儲字符串數組,因爲大多數的用例將使用新的bytes interfacebytearray@MarkPerryman's solution似乎是你最好的選擇,儘管你可以使.encode().decode()透明的一個子類:

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