[Tutor] Converting bytes to a string

Cameron Simpson cs at cskk.id.au
Sun Apr 18 07:19:42 EDT 2021


On 18Apr2021 18:13, Phil <phillor9 at gmail.com> wrote:
>I'm reading serial data from a Pi Pico and I notice that there is what 
>looks like a small 'd' on the end of the string after decoding the 
>byte.
>
>The data is received as b'26.3\r\n' and to convert it to a string I do 
>the following:
>
>s = data.decode()
>s.strip('\r\n')              # at this point there is a mystery 
>character on the end of the string

How do you know this? What does:

    print(repr(s))

show?

If you're doing this interactively, maybe there's some visual indicator 
that there's no end of line?

Also note that the line above does not modify "s". Do you mean:

    s = s.strip('\r\n')

Also be aware that this does not remove the string '\r\n' from the end 
of the line, it removes _all_ occurrences of any '\r' or '\n' characters 
from the start or end of the string. If you have a very recent Python, 
try s.removesuffix('\r\n'), which does remove a fixed string.

>print(s.strip())           # this strips off the small 'd'
>
>I'm wondering what the small, unprintable, 'd' is?

Try printing repr(s) or repr(s.strip()). repr() is your friend for 
seeing exactly what value you have. I'm _guessing_ you're seeing some 
visual indicator of something, but I don't know what environment you're 
testing in.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list