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.

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.