【问题标题】:Using bytearray in Python在 Python 中使用字节数组
【发布时间】:2011-06-28 16:44:03
【问题描述】:

如何在 Python 中实现以下代码(ActionScript)?

var bytes:ByteArray = new ByteArray();
var text:String = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc.";

bytes.writeUTFBytes(text); // write the text to the ByteArray
trace("The length of the ByteArray is: " + bytes.length);    // 70
bytes.position = 0; // reset position
while (bytes.bytesAvailable > 0 && (bytes.readUTFBytes(1) != 'a')) {
    //read to letter a or end of bytes
}
if (bytes.position < bytes.bytesAvailable) {
    trace("Found the letter a; position is: " + bytes.position);     // 23
    trace("and the number of bytes available is: " + bytes.bytesAvailable);    // 47
}

我看过 bytearray 并认为这段代码涵盖了前 4 行:

text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc."
bytes = bytearray(text)
print "The length of the ByteArray is: " + str(len(bytes))

从第 5 行开始,我不确定 Python 的等价物。例如,我找不到 position 方法,但可以使用 bytes[i],其中 i 是我要检索的字节数组中的位置。

谢谢。

【问题讨论】:

    标签: python actionscript bytearray


    【解决方案1】:
    try:
        index = bytes.index('a')
        print "Found letter a in position", index
        # we substract 1 because the array is 0-indexed.
        print "Bytes available:", len(bytes) - index - 1
    except ValueError:
        print "Letter a not found"
    

    这个解决方案比 ActionScript 代码更清晰易读,甚至遵循EAFP python 哲学。

    x[x.index('a')] == 'a',这意味着x.index('a') 将返回a 第一次出现的索引(如果字节数组中没有a,则会引发ValueError)。

    【讨论】:

      【解决方案2】:

      您可以使用字符串(或字节数组)的index 方法来查找值的第一个实例。所以...

      if 'a' in bytes:
          position = bytes.index('a')
          print "Found the leter a; position is:", position
          print "and the number of bytes available is:", len(bytes) - position - 1
      

      【讨论】:

      • nmichaels:当你说索引方法时,你的意思是我写的 bytes[i]
      • @yonatan:不,bytes.index()
      • 感谢您刷新并看到您的完整示例!太棒了!
      猜你喜欢
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2011-11-14
      • 2010-09-29
      • 1970-01-01
      相关资源
      最近更新 更多