Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75733

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

References <64a5643f-a144-4292-9969-9f1743c40ad7@googlegroups.com>
From Thomas Orozco <thomas@orozco.fr>
Date 2014-08-05 14:30 +0200
Subject Re: How to pack a string variable of length 1 as a char using struct.pack?
Newsgroups comp.lang.python
Message-ID <mailman.12666.1407242377.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Tue, Aug 5, 2014 at 2:15 PM, <danwgrace@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)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

How to pack a string variable of length 1 as a char using struct.pack? danwgrace@gmail.com - 2014-08-05 05:15 -0700
  Re: How to pack a string variable of length 1 as a char using struct.pack? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-08-05 22:28 +1000
  Re: How to pack a string variable of length 1 as a char using struct.pack? Thomas Orozco <thomas@orozco.fr> - 2014-08-05 14:30 +0200

csiph-web