Reading line in py serial without \n and \r

Hi,
I am reading serial lines with this command “bs = ser.readline()” but I get several \n and \r in the shell. Any idea how to filter them ?

The answer is the same as the one I gave you here:

Yes, I am replacing “\r” and “\n” using the following code.

[python]
bs = ser.readline()
bs = bs.replace(b’\n’, b’ ‘).replace(b’\r’, b’ ')
print(bs)
[\python]

but I get several places b ’ ’ which I want to delete. How to write empty bytes instead of b ’ ’ ?

Empty bytes is b’’

Hi,

Yes there is b ’ ’ with the print statement that comes in the start and in the end of the line. I am wondering how to filter or remove this b ’ ’ from being printed. What is get now in like this as mentioned below.

[python]
b’ ’
b’ This car is blue ’
b’ ’
[/python]

Yes there is b ’ ’ with the print statement that comes in the start and
in the end of the line. I am wondering how to filter or remove this b ’
’ from being printed. What is get now in like this as mentioned below.

[python]
b’ ’
b’ This car is blue ’
b’ ’
[/python]

While bytes objects are not strings i.e. not text, they do supports a
lot of the string methods because it is often convenient to pretend that
bytes containing only ASCII range bytes are in fact ASCII text.

All that means is that supposing you have a variable bs holding your
bytes. Interactive example:

>>> bs = b'  '
>>> bs
b'  '
>>> bs = bs.strip()
>>> bs
b''
>>> if bs:
...     print(repr(bs))
...

Like strings and other collections, an empty bytes is 'false", a
nonempty bytes is “true”. So you can strip your bytes values and print
them if they are true.

Cheers,
Cameron Simpson cs@cskk.id.au

How can I strip b ’ ’ and just print the main text “This car is blue” as print statement.

Engr,

Use the strip method, as Cameron already suggested.

>>> data = b'  The quick brown fox jumps over the lazy dog.  '

>>> print(data)

b'  The quick brown fox jumps over the lazy dog.  '

>>> print(data.strip())

b'The quick brown fox jumps over the lazy dog.'

If the extra spaces are being inserted in your data by you replacing the

newlines and carriage returns with spaces, you should not replace them

with spaces.

>>> data = b'abcd\nefgh\n'

>>> print(data)

b'abcd\nefgh\n'



>>> print(data.replace(b'\n', b' ')) # replace newlines with spaces

b'abcd efgh '



>>> print(data.replace(b'\n', b'')) # replace newlines with nothing

b'abcdefgh'