Python version: 3.5.2
my codes:
a = b"\xff"
b = a.replace(b"f", b"d")
print(b)
I got b'\xff'
.
I tried another way. Fisrt, i converted bytes to str, then replaced the string.
a = b"\xff"
b = a.decode()
b = b.replace("f", "d")
but through exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I don't know how to fix the problem in python3. What should I do?
There is no b"f"
in b'\xff'
. You type an "f" to enter b'\xff'
, but that's just one of several input methods; the value is the same as, for instance, bytes([255])
. .replace
only replaces bytes that are actually in the string; it doesn't know how you created the string.
Once the string is created, the details of the input method you used to create it are gone. You can't do what you're trying to do for the same reason you can't do '\t'.replace('t', 'n')
to get '\n'
. '\t'
doesn't contain a "t"; you just type a "t" as a means of specifying a tab character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With