Jelle De Loecker
Jelle De Loecker

Reputation: 21945

Reading parts of binary data in a string in Python

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 guess 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)

Upvotes: 0

Views: 362

Answers (1)

unwind
unwind

Reputation: 399823

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.

Upvotes: 3

Related Questions