Windy City
Windy City

Reputation: 49

encode string in Python 3 without unicode \xc2 subsitution

So I was writing some code for some communication with a piece of hardware vis pySerial and i was using python 2.7.7 and everything worked fine, i switched to python 3.4 cause i issues with getting a GUI "framework" installed.

So the problem i have is that I have to encode and decode strings that i send to the COM port, i didn't need to on Python 2.7.7

Here is the string, i understand that the hex value 81 is not ascii but i need to send the string the way it is sent in python 2.7.7.

str = '\x1B\x81'

When i print str I get this:

b'\x1b\xc2\x81'

I assume that the \xc2 is some special unicode character for my \x81, I understand that \x is the escape character for hex and I'm not too sure how Python 2.7.7 writes the string to the serial port.

Would this line:

ser.write('\x1B\x81')

send binary to the serial port? sorta like this:

ser.write('0001 1011 1000 0001')

Also if i send this:

ser.write('\x1B\x81')

to the hardware using Python 3, the hardware just hangs and does nothing, but in Python 2.7 it works.

Upvotes: 2

Views: 1553

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122476

The value obj = '\x1B\x81' in Python 2.7 would be obj = b'\x1B\x81' in Python 3.

The value '\x1B\x81' in Python 3 is text so you're not sending binary to the hardware (it's what's called a Unicode string in Python 2).

Upvotes: 2

Related Questions