Bottom Page

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)
Quote
#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'
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Byte string catenation inefficient in 3.7? RMJFlack 13 389 Aug-18-2019, 05:19 AM
Last Post: RMJFlack
  Byte array is sorted when sending via USB daviddlc68 1 87 Aug-16-2019, 10:11 AM
Last Post: wavic
  understanding output of bytes/raw data rootVIII 3 199 Aug-01-2019, 01:00 PM
Last Post: rootVIII
  pickle docs say bytes in one place, strings in another Skaperen 2 94 Jul-29-2019, 05:13 PM
Last Post: Skaperen
  raw byte of integer jonnin 4 189 Jul-22-2019, 03:48 AM
Last Post: jonnin
  printing a bytes string Skaperen 2 105 Jul-21-2019, 03:42 AM
Last Post: Skaperen
  How to replace matching rows SriMekala 2 143 Jul-13-2019, 09:43 AM
Last Post: SriMekala
  replace white space with a string, is this pythonic? Skaperen 1 161 Jun-18-2019, 11:36 PM
Last Post: metulburr
  HELP: String of Zero's and One's to binary byte schwasskin 1 1,134 May-19-2019, 07:31 AM
Last Post: heiner55
  Reading data from serial port as byte array vlad93 1 811 May-18-2019, 05:26 AM
Last Post: heiner55

Forum Jump:


Users browsing this thread: 1 Guest(s)