-1

I tried some code from a python [tutorial for python struct][1]:

import struct
import binascii

values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packed_data = s.pack(*values)

and got error

Input In [4], in <cell line: 1>()
----> 1 s.pack(1, 'ab', 2.7)

error: argument for 's' must be a bytes object

Where is the problem?

[1] http://pymotw.com/2/struct/

zell
  • 9,830
  • 10
  • 62
  • 115
  • 1
    The problem is that you're passing a string, not bytes. You're reading Python 2.x examples, note the changes compared with https://pymotw.com/3/struct/index.html. – jonrsharpe Jul 03 '22 at 14:36
  • 1
    Near-exact duplicate (same example): [Struct.Error, Must Be a Bytes Object?](https://stackoverflow.com/questions/10082623/struct-error-must-be-a-bytes-object) – esqew Jul 03 '22 at 14:37

1 Answers1

0

The string must be a byte string, This should work

values = (1, bytes('ab','utf-8'), 2.7)
packed_data = s.pack(*values)
Himanshu Poddar
  • 7,112
  • 10
  • 47
  • 93
  • 1
    I wouldn't downvote for this (and didn't do so here), but the _Answer Well-Asked Questions_ section of the [How to Answer](https://stackoverflow.com/help/how-to-answer) page in the Help Center instructs you not to answer questions that "have been asked and answered many times before". – Charles Duffy Jul 03 '22 at 14:41
  • I answered it before esqew marked it as duplicate – Himanshu Poddar Jul 03 '22 at 14:42
  • A great answer in my opinion, which shows. my tutorial has a bug. – zell Jul 03 '22 at 14:47
  • @zell, not a bug, just outdated. You need to find a tutorial made for Python 3. – Charles Duffy Jul 03 '22 at 15:46