Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to clean UART string
#1
Hi,

I am saving the UART data in the text file which appear as.

b' All is well '

How can I remove the b' in the start and ' at the end ?
Reply
#2
If what you want removed is always in the same position in the string, it is as simple as slicing the ends off like this:
uart_string = "b' All is well '"
output_string = uart_string [2: -1]
print (output_string)
Output:
All is well
Reply
#3
>>> foo = b' All is well '
>>> foo.decode()
' All is well '
>>> str(foo, encoding='utf8')
' All is well '

bytes.decode() docs
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
The b in front of the quotes tells Python that these are bytes.
If you don't assign the result to a name, the REPL prints the object in its representation form, which also includes the quotes.

If you decode the bytes to a str, then the quotes are only shown in representation (without the leading b).

If you print the resulting str, you won't see the quotes at the start and end of the str, but if you print bytes, then the representation is printed to console.


data = b"123" # bytes
print("bytes", data)
print("str", data.decode())

# decode without encoding, will use the system default encoding
# it's motsly everywhere uft8
# sometimes it's latin1 (in old Windows Terminal e.G.)
Output:
bytes b'123' str 123
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Why do you want to remove the b'' parts? If you want to save it as a string, why did you have it as bytes?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UART & I2C slow down a loop trix 4 631 Dec-28-2023, 05:14 PM
Last Post: trix
  Can i clean this code ? BSDevo 8 957 Oct-28-2023, 05:50 PM
Last Post: BSDevo
  Clean Up Script rotw121 2 1,021 May-25-2022, 03:24 PM
Last Post: rotw121
  UART Serial Read & Write to MP3 Player Doesn't Work bill_z 15 5,853 Jul-17-2021, 04:19 PM
Last Post: bill_z
Smile send hexadecimal package variable UART santos20 2 2,206 Oct-30-2020, 11:40 AM
Last Post: Larz60+
  wrong data reading on uart fahri 6 3,390 Sep-29-2020, 03:07 PM
Last Post: Larz60+
  How to clean session mqtt SayHiii 0 2,010 Dec-09-2019, 07:56 AM
Last Post: SayHiii
  how to clean up unstarted processes? Skaperen 2 2,257 Aug-27-2019, 05:37 AM
Last Post: Skaperen
  sched.scheduler -> clean denisit 1 2,887 Nov-28-2018, 09:52 AM
Last Post: Gribouillis
  clean unicode string to contain only characters from some unicode blocks gmarcon 2 3,992 Nov-23-2018, 09:17 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020