[英]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).所以这个fake_bytes
字符串是一个以字节编码的文本,并在视觉上转换为字符串(不解码字节)。
The question is how to convert fake_bytes
again to bytes without encoding its contents again to get something like that:问题是如何将fake_bytes
再次转换为字节而不再次对其内容进行编码以获得类似的东西:
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
是与字符串内容相同的字节,稍后可以解码为原始文本:
>>> real_bytes.decode()
check ✔️
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.