开发者

Using bytearray in Python

开发者 https://www.devze.com 2023-02-10 18:24 出处:网络
How can I implement the below code (ActionScript) in Python? var bytes:ByteArray = new ByteArray(); var text:String = \"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc.\";

How can I implement the below code (ActionScript) in Python?

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
开发者_Python百科    trace("and the number of bytes available is: " + bytes.bytesAvailable);    // 47
}

I've had a look at bytearray and think this code covers the first 4 lines:

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

From line 5 onwards I'm not sure of the Python equivalent. For example, I couldn't find a position method, but can use bytes[i] where i is the position in the bytearray I want to retrieve.

Thank you.


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"

This solution is much clearer and human-readable than the ActionScript code, and it even follows the EAFP python philosophy.

x[x.index('a')] == 'a', this means that x.index('a') will return the index of the first occurrence of a (and will raise a ValueError if there is no a in the bytearray).


You can use the index method of the string (or bytearray) to find the first instance of a value. So...

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号