【问题标题】:Array of characters in python 3?python 3中的字符数组?
【发布时间】:2016-09-05 15:43:55
【问题描述】:

Python 2.7 中,我可以像这样创建一个字符数组:

#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: 不能使用 str 来初始化 typecode 'c' 的数组

【问题讨论】:

  • 警告:这基本上询问如何存储字符,然后接受将编码字符存储为字节数组的答案。如果您没有注意到,那并不是真正的字符数组。基本上这意味着该人没有得到它:使用 string.

标签: python arrays python-3.x


【解决方案1】:

使用字节数组'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'

【讨论】:

    【解决方案2】:

    python 开发人员似乎不再支持在数组中存储字符串,因为大多数用例将使用新的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())
    

    【讨论】:

      【解决方案3】:

      除了the answer of Mark Perryman

      >> x.frombytes('hellow world'.encode())
      >>> x
      array('b', [116, 101, 115, 116, 104, 101, 108, 108, 111, 119, 32, 119, 111, 114, 108, 100])
      >>> x.tostring()
      b'testhellow world'
      >>> x[1]
      101
      >>> x[1]^=0x1
      >>> x[1]
      100
      
      >> x.tobytes().decode()
      'wdsthellow world'
      >>> x.tobytes
      <built-in method tobytes of array.array object at 0x11330b7b0>
      >>> x.tobytes()
      b'wdsthellow world'
      
      

      没错,我最近需要从我的数组列表中转换一个特殊字节, 尝试了各种方法,然后得到新的简单方法:x[1]^=0x1,和 可以通过array.array['b', &lt;my bytes list&gt;]轻松获取数组

      【讨论】:

      • 欢迎来到 Stack Overflow,请注意,您不需要复制其他人的答案。请编辑您的答案以仅包含您自己的答案。
      猜你喜欢
      • 2019-05-13
      • 2018-08-07
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多