简体   繁体   中英

Arduino - python read serial layout

I'm using pyserial to read some values from my Arduino. Using serial.readlines() gives me an array with all the values, but these values look like:

  • b'l: steer left \\n'
  • b'r: steer right \\n'

How can I get rid of these b' and \\n' ? Replacing them didn't work…

b is denoting the encoding the string is in – it isn't actually part of the string, so you can't replace it. Similarly with each ' – they denote that it is a string. ( 4 and '4' are two different things, but print(…) either of them and you'll get identical results.) The only thing you need to do is remove the last character (newline) with

myvar[:-1]

To re-encode the string, this should be sufficient:

b'string'.decode('ascii')

If you're using Unicode at all, use

b'string'.decode('utf-8')

instead. See the Python manual for more information to this end.


Python 3.4.2 (default, Oct 19 2014, 17:55:38) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> b'l: steer left \n'
b'l: steer left \n'
>>> _.decode('ascii')
'l: steer left \n'
>>> print(_)
l: steer left 

>>> exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM