How to pack a string variable of length 1 as a char using struct.pack?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 5 08:28:13 EDT 2014


danwgrace at 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')

Here you use a byte string of length 1, b'1'.


> Whereas this causes an error "char format requires a bytes object of
> length 1": 
> s = '1' 
> p = struct.pack('c', s)

Here you use a Unicode string of length 1, '1'.

Do this instead:

s = b'1'
p = struct.pack('c', s)


-- 
Steven




More information about the Python-list mailing list