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?
Answers:
From the error message, I get that you are running Python2 (works in Python3). Assuming that message is a string:
-
Python 3 ([Python 3.Docs]: class bytes([source[, encoding[, errors]]])):
byte_command = b"x01"
sock.send(byte_command + bytes(message, 'UTF-8'))
-
Python 2 (where bytes and str are the same):
byte_command = "x01"
sock.send(byte_command + message)
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).
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'))
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?
From the error message, I get that you are running Python2 (works in Python3). Assuming that message is a string:
-
Python 3 ([Python 3.Docs]: class bytes([source[, encoding[, errors]]])):
byte_command = b"x01" sock.send(byte_command + bytes(message, 'UTF-8'))
-
Python 2 (where bytes and str are the same):
byte_command = "x01" sock.send(byte_command + message)
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).
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'))