在Python中,我得到了一个使用Quoted-Printable编码的字符串。
mystring="=AC=E9"
这个字符串应该打印为
é
所以我想要解码并使用UTF-8重新编码它。我猜这是可能的。我知道可以通过
import quopri
quopri.decodestring('=A3=E9')
但是,接下来我完全不知道该怎么做。您如何对此字符串进行解码/编码以正确打印?
在Python中,我得到了一个使用Quoted-Printable编码的字符串。
mystring="=AC=E9"
这个字符串应该打印为
é
所以我想要解码并使用UTF-8重新编码它。我猜这是可能的。我知道可以通过
import quopri
quopri.decodestring('=A3=E9')
import quopri
编码:
您可以使用quopri.encodestring()将字符'é'编码为Quoted-Printable。它接受一个字节对象,并返回QP编码的字节对象。
encoded = quopri.encodestring('é'.encode('utf-8'))
print(encoded)
该代码输出b'=C3=A9'(而不是问题中指定的“=AC=E9”或“=A3=E9”)
解码:
mystring = '=C3=A9'
decoded_string = quopri.decodestring(mystring)
print(decoded_string.decode('utf-8'))
quopri.decodestring() 返回一个字节(bytes)对象, 该对象使用utf-8进行编码(这可能是您想要的)。如果您希望打印字符'é',请使用.decode()解码utf-8编码的字节对象并将'utf-8'作为参数传递。
大家好,我不确定为什么,但是这个函数似乎有效:
from email.parser import Parser
def decode_email(msg_str):
p = Parser()
message = p.parsestr(msg_str)
decoded_message = ''
for part in message.walk():
charset = part.get_content_charset()
if part.get_content_type() == 'text/plain':
part_str = part.get_payload(decode=1)
decoded_message += part_str.decode(charset)
return decoded_message
import quopri
mystring="=AC=E9"
decoded_string=quopri.decodestring(mystring)
print(decoded_string.decode('windows-1251'))