[英]Using bytearray in Python
如何在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是否等效。 例如,我找不到位置方法,但是可以使用bytes [i] ,其中i是我要檢索的字節數組中的位置。
謝謝。
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
(和將引發ValueError
,如果沒有a
在字節數組)。
您可以使用字符串(或字節數組)的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.