-2

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?

Jacobian
  • 10,122
  • 29
  • 128
  • 221
  • You should probably explain what is your general goal because there is probably a better way to reach it. – Eric Levieil Jun 08 '15 at 17:07
  • In PHP I implemented a short code snippet that compares two documents and collects all the changes. If I have the initial version of the document and the history of all the changes (which is much less, than if I stored whole documents), then I can easily restore the document at any point in time. I decided to do the same thing in Python. – Jacobian Jun 08 '15 at 17:12
  • Oh, actually I think, I found a better solution based on `bytearray` function in Python. – Jacobian Jun 08 '15 at 17:15
  • 1
    Have you checked https://docs.python.org/2/library/difflib.html ? – Eric Levieil Jun 08 '15 at 18:08
  • These methods are great! Thanks! But in my case, I think, handmade tiny methods will be sufficient – Jacobian Jun 08 '15 at 18:34
  • Or, I would say that these methods will be helpful for thorough investigation of changes. – Jacobian Jun 08 '15 at 18:35

1 Answers1

4

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.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80