<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Tue, Aug 5, 2014 at 2:15 PM, <span dir="ltr"><<a href="mailto:danwgrace@gmail.com" target="_blank">danwgrace@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
Hi,<br>
How to pack a string variable of length 1 as a char using struct.pack?<br>
The following works fine:<br>
p = struct.pack('c', b'1')<br>
<br>
Whereas this causes an error "char format requires a bytes object of length 1":<br>
s = '1'<br>
p = struct.pack('c', s)<br>
<br>
I need to pack a variable rather than a literal.<br></blockquote><div><br></div>I assume you are using Python 3. In Python 3, s = '1' is a *unicode string*, not a *bytes object*.<div><br></div><div>You need to convert your string to a bytes object by encoding it. </div>
<div><br></div><div>However, be mindful that some characters may actually require multiple bytes to be encoded:</div><div><br></div><div> struct.pack('c', s.encode('ascii')) </div><div><br></div><div>(You can of course use e.g. 'utf-8' as the encoding here)</div>
</div></div></div>