5

I need to create a Python string consisting of non-ascii bytes to be used as a command buffer in a C module. I can do that if I write the string by hand:

mybuffer = "\x00\x00\x10"

But I cannot figure out how to create the string on the fly if I have a set of integers which will become the bytes in the string. Concatenating an integer with a string is a TypeError.

So if I have a list of integers lets say:

myintegers = [1, 2, 3, 10]

How can I convert that into a string "\x01\x02\x03\x0A"

I am using Python 2.6.

3 Answers 3

4

u''.join(map(unichr, myintegers)) will do what you want nicely.

Sign up to request clarification or add additional context in comments.

2 Comments

Leave off the leading u and use chr instead of unichr if you won't go above 256.
Better yet, use b'' so that 2to3 will recognize it as bytes instead of str.
3

Python 2.X

''.join(chr(i) for i in myintegers)

Python 3.X

bytes(myintegers)

Comments

0
In [28]: import struct

In [29]: struct.pack('{0}B'.format(len(myintegers)),*myintegers)
Out[29]: '\x01\x02\x03\n'

Note that

In [47]: '\x01\x02\x03\n'=="\x01\x02\x03\x0A"
Out[47]: True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.