DildoShwagginz
DildoShwagginz

Reputation: 13

Python3 string conversion issue

I have a function:

def push(push):
   ser.write(push + '\r')
   pull = ser.read(11)  
   return pull

and i call it like this:

out = push("ka " + dp_id + " ff")

It turns out to work very well with python2 but when I use python 3 I get the Error:

unicode strings are not supported, please encode to bytes: 'ka 01 ff\r'

Now if I do this:

out = push(b"ka " + display_id + " ff")

I get the Error:

can't concat bytes to str

Im confused. What does help?

Upvotes: 1

Views: 87

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

The problem has nothing to do with push itself. You write:

b"ka " + display_id + " ff"
# ^bytes ^string      ^string

(the b prefix says you actually write a sequence of bytes).

so that won't work. You can encode a string to a byte array with .encode() and use the b prefix on the last string. So:

b"ka " + display_id.encode() + b" ff"
# ^bytes ^bytes                ^bytes

Upvotes: 5

Related Questions