In php, unpack() has the "*" flag which means "repeat this format until the end of input". For example, this prints 97, 98, 99
$str = "abc";
$b = unpack("c*", $str);
print_r($b);
Is there something like this in python? Of course, I can do
str = "abc"
print struct.unpack("b" * len(str), str)
but I'm wondering if there is a better way.
There is no such facility built into
struct.unpack
, but it is possible to define such a function:In Python 3.4 and later, you can use the new function
struct.iter_unpack
.Let's say we want to unpack the array
b'\x01\x02\x03'*3
with the repeating format string'<2sc'
(2 characters followed by a single character, repeat until done).With
iter_unpack
, you can do the following:If you want to un-nest this result, you can do so with
itertools.chain.from_iterable
.Of course, you could just employ a nested comprehension to do the same thing.