Search code examples
pythonpython-3.xreplacebinaryfiles

Can't replace hex in bytes with python


>>> data=b'\x11\x22'
>>> data.hex()
'1122'
>>> len(data)
2
#let's try to replace data ....
>>> data.replace(b'1122',b'3344').hex()
'1122'

Why I can't replace with replace 0x1122 to 0x3344 ?


Solution

  • Because your bytes doesn't contain 1122 (four discrete ASCII values representing '1', '1', '2', '2'), it contains \x11\x22 (two discrete raw byte encodings, 0x11, 0x22). If you want to replace the raw byte values, provide them for the replacement, e.g.

    data.replace(b'\x11\x22',b'\x33\x44').hex()