如何在base64解码后将\ x转换为可读的东西?

时间:2015-11-01 00:20:16

标签: python unicode base64 ascii

我尝试将以下Base64字符串解码为可读文本。

T2ggeWVhaCEgAQ==

我使用Python Base64库来实现这一目标。但是,当我这样做时,我得到:

>>> base64.b64decode("T2ggeWVhaCEgAQ==")
'Oh yeah! \x01'

什么是\x01

我如何解码所有文字都是可读的,而且我没有得到任何奇怪的符号?

3 个答案:

答案 0 :(得分:1)

您可以过滤掉不可读的字符:

from string import printable
print ''.join(c for c in base64.b64decode('T2ggeWVhaCEgAQ==') if c in printable)

答案 1 :(得分:1)

'\x01'是Python 2中bytes的文本表示。'\x01'是单个字节。 ASCII printable range中的字节代表自己,例如,您看到'O'而不是'\x4f'

>>> b'\x4f\x68\x20\x79\x65\x61\x68\x21\x20\x01'
'Oh yeah! \x01'

删除所有“怪异”字节(以保留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,例如'\t'(标签),'\n'(换行符)。要排除它们,只留下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! 

答案 2 :(得分:0)

Base64编码数据的最后一个字节是十六进制01.这不是任何常用编码中的可打印字符;没有把它变成“可读的文本”而没有把它变成它不是的东西。