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?

4
  • 1
    byte_command = 0x01, it is an int, if you want the bytes representation, use byte_command = b"\x01". Commented Feb 21, 2018 at 17:10
  • @CristiFati still does not work Commented Feb 21, 2018 at 17:18
  • The proximal cause of you error is passing an invalid argument to bytes()...If message is a string, then you need message.encode()... But is this really Python 3? Commented Feb 21, 2018 at 17:23
  • Nevermind I accidentally used python 2 -,- Commented Feb 21, 2018 at 17:26

2 Answers 2

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

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

4 Comments

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
Apperently the bytes I am sending have to be in hex representation - how would I do that?
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).
I created a new question as you advised: stackoverflow.com/questions/48915590/…
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'))

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.