在Python中使用bytearray
我该如何把下面的代码(ActionScript)用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
trace("and the number of bytes available is: " + bytes.bytesAvailable); // 47
}
我看过bytearray,觉得这段代码的前四行可以用Python来写:
text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc."
bytes = bytearray(text)
print "The length of the ByteArray is: " + str(len(bytes))
从第五行开始,我就不太确定Python里有什么对应的写法了。例如,我找不到一个叫position的方法,但可以用bytes[i]来获取bytearray中第i个位置的内容。
谢谢。
2 个回答
1
你可以使用字符串(或者字节数组)的 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
2
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
错误)。