且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改“可列印的”编码为“utf-8”

更新时间:2023-11-27 13:50:46

quopri module 可以将这些字节转换为未编码的字节流。你需要解码那些从他们所在的字符集,然后编码回 utf-8

 >>> b = quopri.decodestring('= C4 = EE = E1 = F0 = FB = E9 = E4 = E5 = ED = FC')
>>> print(b.decode('windows-1251'))
Добрыйдень


I am trying to read email with imaplib. I get this mail body:

=C4=EE=E1=F0=FB=E9 =E4=E5=ED=FC!  

That is Quoted-printable encoding.
I need to get utf-8 from this. It should be Добрый день!

I googled it, but it is too messy with Python's versions. It is already unicode in Python 3, I cann't use .encode('utf-8') here.

How can I change this to utf-8?

The quopri module can convert those bytes to an unencoded byte stream. You need to then decode those from whatever character set they're in, then encode back to utf-8.

>>> b = quopri.decodestring('=C4=EE=E1=F0=FB=E9 =E4=E5=ED=FC')
>>> print(b.decode('windows-1251'))
Добрый день