'How to convert bytes represented as a string to the real bytes
Suppose we have a string that looks like this:
fake_bytes = "b'This is a check - \xe2\x9c\x94\xef\xb8\x8f'"
So this fake_bytes string is a text that is encoded in bytes and visually converted to string (without decoding the bytes).
The question is how to convert fake_bytes again to bytes without encoding its contents again to get something like that:
real_bytes = b'This is a check - \xe2\x9c\x94\xef\xb8\x8f'
The real_bytes is bytes with the same contents as a string and can be decoded to the original text later:
>>> real_bytes.decode()
check ✔️
Solution 1:[1]
Python 3.9.7 (default, Sep 16 2021, 13:09:58)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> fake_bytes = "b'This is a check - \xe2\x9c\x94\xef\xb8\x8f'"
>>> x = fake_bytes.encode('utf-8')[2:-1]
>>> x
b'This is a check - \xc3\xa2\xc2\x9c\xc2\x94\xc3\xaf\xc2\xb8\xc2\x8f'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Li-chih Wu |
