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
  Int.From_Bytes Method - Conversion of Non-Escaped Bytes Objects new_coder_231013 1 273 Jan-17-2024, 09:13 PM
Last Post: Gribouillis
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,178 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  Change HID bytes using pywinusb.hid Stealthrt 0 589 Jul-06-2023, 03:36 PM
Last Post: Stealthrt
  TypeError: a bytes-like object is required ZeroX 13 3,841 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 4,675 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 2,561 Jul-25-2022, 03:19 PM
Last Post: deanhystad
Question How to understand the received bytes of ser.read? pf2022 3 1,921 Mar-24-2022, 11:37 AM
Last Post: pf2022
  bytes object saved as .mp4 jttolleson 10 5,752 Feb-25-2022, 02:42 PM
Last Post: jttolleson
  How to convert 4 bytes to an integer ? GiggsB 11 6,603 Jan-20-2022, 03:37 AM
Last Post: GiggsB
  Get amount of bytes in a file chesschaser 1 1,545 Aug-23-2021, 03:24 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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