如何将 base64 解码后的 \x 转换为可读的内容?
How to convert \x after base64 decoding into something readable?
我正在尝试将以下 Base64 字符串解码为可读文本。
T2ggeWVhaCEgAQ==
我正在使用 Python Base64 库来执行此操作。但是,当我这样做时,我得到:
>>> base64.b64decode("T2ggeWVhaCEgAQ==")
'Oh yeah! \x01'
什么是\x01
?
我该如何解码才能使所有文本都可读并且不会出现任何奇怪的符号?
Base64 编码数据的最后一个字节是十六进制 01。这不是任何常用编码中的可打印字符;如果不把它变成它不是的东西,就没有办法让它变成 "readable text"。
您可以过滤掉不可读的字符:
from string import printable
print ''.join(c for c in base64.b64decode('T2ggeWVhaCEgAQ==') if c in printable)
'\x01'
是 Python 2 中 bytes
的文本表示。 '\x01'
是单个字节。 ASCII printable range 中的字节代表它们自己,例如,您看到 'O'
而不是 '\x4f'
:
>>> b'\x4f\x68\x20\x79\x65\x61\x68\x21\x20\x01'
'Oh yeah! \x01'
删除所有 "weird" 字节(保留 string.printable
中的字符):
#!/usr/bin/env python
import string
weird = bytearray(set(range(0x100)) - set(map(ord, string.printable)))
print(b'Oh yeah! \x01'.translate(None, weird).decode())
# -> Oh yeah!
string.printable
包含一些 non-printable characters such as '\t'
(tab), '\n'
(newline). To exclude them too and to leave only printing character:
printing_chars = range(0x20, 0x7e + 1)
weird = bytearray(set(range(0x100)) - set(printing_chars))
print(b'Oh yeah! \x01'.translate(None, weird))
# -> Oh yeah!
我正在尝试将以下 Base64 字符串解码为可读文本。
T2ggeWVhaCEgAQ==
我正在使用 Python Base64 库来执行此操作。但是,当我这样做时,我得到:
>>> base64.b64decode("T2ggeWVhaCEgAQ==")
'Oh yeah! \x01'
什么是\x01
?
我该如何解码才能使所有文本都可读并且不会出现任何奇怪的符号?
Base64 编码数据的最后一个字节是十六进制 01。这不是任何常用编码中的可打印字符;如果不把它变成它不是的东西,就没有办法让它变成 "readable text"。
您可以过滤掉不可读的字符:
from string import printable
print ''.join(c for c in base64.b64decode('T2ggeWVhaCEgAQ==') if c in printable)
'\x01'
是 Python 2 中 bytes
的文本表示。 '\x01'
是单个字节。 ASCII printable range 中的字节代表它们自己,例如,您看到 'O'
而不是 '\x4f'
:
>>> b'\x4f\x68\x20\x79\x65\x61\x68\x21\x20\x01'
'Oh yeah! \x01'
删除所有 "weird" 字节(保留 string.printable
中的字符):
#!/usr/bin/env python
import string
weird = bytearray(set(range(0x100)) - set(map(ord, string.printable)))
print(b'Oh yeah! \x01'.translate(None, weird).decode())
# -> Oh yeah!
string.printable
包含一些 non-printable characters such as '\t'
(tab), '\n'
(newline). To exclude them too and to leave only printing character:
printing_chars = range(0x20, 0x7e + 1)
weird = bytearray(set(range(0x100)) - set(printing_chars))
print(b'Oh yeah! \x01'.translate(None, weird))
# -> Oh yeah!