Python Forum
replace bytes with other byte or bytes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace bytes with other byte or bytes
#1
Am trying to replace all occurrences of bytes with other byte or bytes.
In the variable myvalue I want to replace badstuff with goodstuff every time it occurs

PyPdf2 returns a value like this from a multi line text box in a fillable PDF.
b"line1\rline2\rline3\rline4"

However, I need to write this without the quotes to a .TXT file
"line1~line2~line3~line4"
or like this if it has to be the same number of bytes
"line1~~line2~~line3~~line4"

the example syntax below gets this message
Syntax Error: invalid syntax: <string>, line 5, pos 5

myanswer =b"line1\rline2\rline3\rline4" print (myanswer) badstuff = b"\r" goodstuff = b"~" if in(myanswer,badstuff): myanswer=re.sub(badstuff,goodstuff,myanswer) print (myanswer)
Reply
#2
(Feb-02-2019, 10:23 PM)BigOldArt Wrote: Am trying to replace all occurrences of bytes with other byte or bytes.
replace() dos this.
>>> myanswer = b"line1\rline2\rline3\rline4" >>> myanswer.replace(b'\r', b'~') b'line1~line2~line3~line4'
If want it to be string,also default text(Unicode) in Python 3.
>>> myanswer = b"line1\rline2\rline3\rline4" >>> myanswer = myanswer.decode() # Same as decode('utf-8') >>> myanswer 'line1\rline2\rline3\rline4' >>> myanswer.replace('\r', '~') 'line1~line2~line3~line4'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 10 26,597 May-26-2025, 01:55 PM
Last Post: deanhystad
  UART how to read 300 bytes ? trix 7 2,351 Aug-22-2024, 12:54 PM
Last Post: trix
  Int.From_Bytes Method - Conversion of Non-Escaped Bytes Objects new_coder_231013 2 3,949 Apr-06-2024, 04:24 PM
Last Post: new_coder_231013
  Change HID bytes using pywinusb.hid Stealthrt 0 2,054 Jul-06-2023, 03:36 PM
Last Post: Stealthrt
  TypeError: a bytes-like object is required ZeroX 13 23,167 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 9,805 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 6,578 Jul-25-2022, 03:19 PM
Last Post: deanhystad
Question How to understand the received bytes of ser.read? pf2022 3 4,307 Mar-24-2022, 11:37 AM
Last Post: pf2022
  bytes object saved as .mp4 jttolleson 10 9,838 Feb-25-2022, 02:42 PM
Last Post: jttolleson
  How to convert 4 bytes to an integer ? GiggsB 11 18,741 Jan-20-2022, 03:37 AM
Last Post: GiggsB

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.