Python Forum

Full Version: replace bytes with other byte or bytes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
(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'