On Tue, Aug 5, 2014 at 2:15 PM, <danwgr...@gmail.com> wrote: > Hi, > How to pack a string variable of length 1 as a char using struct.pack? > The following works fine: > p = struct.pack('c', b'1') > > Whereas this causes an error "char format requires a bytes object of > length 1": > s = '1' > p = struct.pack('c', s) > > I need to pack a variable rather than a literal. >
I assume you are using Python 3. In Python 3, s = '1' is a *unicode string*, not a *bytes object*. You need to convert your string to a bytes object by encoding it. However, be mindful that some characters may actually require multiple bytes to be encoded: struct.pack('c', s.encode('ascii')) (You can of course use e.g. 'utf-8' as the encoding here)
-- https://mail.python.org/mailman/listinfo/python-list