0

Hi,

I am trying to pack a unicode string of 40 bytes using the pack method.

data = pack('<8sB40s',
                    asc_time,
                    language_id,
                    message)

it throws the following error:
struct.error: argument for 's' must be a string

What is the argument for a unicode string?
Thanks in advance.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by d5e5
0

I don't know. I'm sure you've googled and I've googled and can't find any struct format argument that allows you to pack a unicode string. What you could do is encode the unicode string into an 8-bit string, which the 's' argument will accept and allow you to pack. Which encoding you use depends on what characters will be in your string. In the following I use the 'utf-8' encoding:

#!/usr/bin/env python
import struct
asc_time = "10:15 AM"
language_id = 2
#message = unicode("This is a test")
umessage = u'This is a test'
smessage = umessage.encode('utf-8')
data = struct.pack('<8sB40s',
                    asc_time,
                    language_id,
                    smessage)

print "Printing the packed data:"
print data

print "\nPrinting the unpacked data:"
print struct.unpack('<8sB40s', data)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.