0

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?

Curunir
  • 1,186
  • 2
  • 13
  • 30

2 Answers2

1

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).

CristiFati
  • 38,250
  • 9
  • 50
  • 87
  • Yes message is a string. But strangely I get for message="AUTH" I get: 01 65 85 84 72 16 and not 01 41 55 54 48 as I would expect it – Curunir Feb 21 '18 at 18:19
  • Apperently the bytes I am sending have to be in hex representation - how would I do that? – Curunir Feb 21 '18 at 18:53
  • I see, the 2nd value list is the hex representation of the ones in the 1st one. The bytes that you're sending? Meaning `message`? you should edit the question, and add the message as it is and how it should be (althought that would be a different question). – CristiFati Feb 21 '18 at 19:54
  • I created a new question as you advised: https://stackoverflow.com/questions/48915590/python-3-convert-string-to-hex-bytes – Curunir Feb 21 '18 at 21:14
0

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'))