Python 3 Concat Single Byte with String Bytes

Question:

I need to concat a single byte with the bytes I get from a parameter string.

byte_command = 0x01
socket.send(byte_command + bytes(message, 'UTF-8'))

but I get this error:

socket.send(byte_command + bytes(message, 'UTF-8'))
TypeError: str() takes at most 1 argument (2 given)

I assume this happens because I am using the string concat operator – how do I resolve that?

Asked By: Curunir

||

Answers:

From the error message, I get that you are running Python2 (works in Python3). Assuming that message is a string:

I also renamed the socket to sock so it doesn’t clash with the socket module itself.
As everyone suggested, it’s recommended / common to do the transformation using message.encode("utf8") (in Python 3 the argument is not even necessary, as utf8 is the default encoding).

More on the differences (although question is in different area): [SO]: Passing utf-16 string to a Windows function (@CristiFati’s answer).

Answered By: CristiFati

From that error message, it looks like you are using python2, not python3. In python2, bytes is just an alias for str, and str only takes one argument.

To make something that works in python2 and python3, use str.encode rather than bytes:

byte_command = b'0x01'
socket.send(byte_command + message.encode('UTF-8'))
Answered By: Peter Moore
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.