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

Thomas Orozco thomas at orozco.fr
Tue Aug 5 08:30:24 EDT 2014


On Tue, Aug 5, 2014 at 2:15 PM, <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')
>
> 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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140805/482f44a1/attachment.html>


More information about the Python-list mailing list