开发者

Reading parts of binary data in a string in Python

开发者 https://www.devze.com 2023-02-26 03:08 出处:网络
When you use the .read(n) method on a file object in python you get n amount of bytes back. What if I first load a file in a string, is there some function that lets me do the same thing?

When you use the .read(n) method on a file object in python you get n amount of bytes back. What if I first load a file in a string, is there some function that lets me do the same thing?

Because I 开发者_如何学Goguess it's not as easy filestring[0:5], because of different types of encoding. (And I don't really want to pay attention to that, the file read can be a text file in any format or a binary file)


If string is type str (not a Unicode string, type unicode), then it's a byte string and slicing will work as expected:

prefixed_bits = "extract this double:\xc2\x8eET\xfb!\t@"
pos = prefixed_bits.index(":") + 1
print "That looks like the value %f" % struct.unpack("d", prefixed_bits[pos:pos+8])

This prints 3.141593, the binary representation of which is encoded in the string literal.

0

精彩评论

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