Search code examples
pythonunpack

Python unpack like in PHP


In PHP I will do it like this:

$res = unpack('C*', "string");

And $res variable will be an array of size 6:

Array ( [1] => 115 [2] => 116 [3] => 114 [4] => 105 [5] => 110 [6] => 103 ) 

I want to do the same trick in Python. I tried this:

>>> from struct import unpack
>>> unpack("s","string")

But in this case I get an error:

struct.error: unpack requires a string argument of length 1

I just wonder - why of length 1 if "s" format stands for string? And how can I implement the same thing, like in PHP?


Solution

  • That's because struct.unpack format s means "a string". By default it's a 1-char string, otherwise you would have to specify the length, e.g. 10s for a 10-char string.

    Anyway, Python strings already behave like immutable arrays of characters, so that you can do s[3] and obtaining the 4th (zero-based) char. If you need to explicitely explode the string into a dictionary (akin to PHP associative array), you could do:

     s = dict(enumerate("string"))
    

    but I strongly recommend against doing so.