python 字符编码问题

1、quopri  该类可以用来表示大部分的字符包括西欧字符。该字符编码之后还是可读字符

但是一些字符还是无法被解码。但是在3.3下面已经可以正确的编码和解码这些字符了。

>>> import quopri
>>> encoded = quopri.encodestring(bytes('I will have just a soupcon of soup.', 'utf-8'))
>>> print (encoded)
b'I will have just a soupcon of soup.'
>>> print (quopri.decodestring (encoded ))
b'I will have just a soupcon of soup.'

所以在一般的使用时可以使用该类进行编码和解码

2、 Base64 该类使用的是用二进制进行编码,对任何的字符能够进行正常的编码和解码。但是在编码之后,该字符是无法进行正常阅读的数据。

>>> import base64
>>> encoded = base64.encodestring(bytes('I will have just a soupcon of soup.', 'utf-8'))
>>> print (encoded)
b'SSB3aWxsIGhhdmUganVzdCBhIHNvdXBjb24gb2Ygc291cC4=
'
>>> print (base64.decodestring(encoded ))
b'I will have just a soupcon of soup.'

使用该编码的数据的时候可以对一些进行二进制的编码。

这两个类还有一些区别:使用quopri进行可视字符编码,将比base64更短的字符。但是使用二进制的数据进行编码,base64将比quopri更短的长度。

>>> length = 10000
>>> randomBinary = ''.join([chr(random.randint(0, 255)) for x in range(0, length)])
>>> len(quopri.encodestring(bytes(randomBinary, 'utf-8')))/float(length)
3.8584
>>> len(base64.encodestring(bytes(randomBinary, 'utf-8')))/float(length)
2.0312

所以这里按照RFC1521的说法就是quopri是可读型,base64是编码型

原文地址:https://www.cnblogs.com/cxiaoln/p/3669703.html