编码问题:在Python中解码带引号的可打印字符串 [英] Encoding issue : decode Quoted-Printable string in Python

查看:252
本文介绍了编码问题:在Python中解码带引号的可打印字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我得到了一个以 Quoteed-Printable编码

In Python, I got a string encoded in Quoted-Printable encoding

mystring="=AC=E9"

此字符串应打印为

é

所以,我想我想对其进行解码并以UTF-8进行编码.我了解可以通过以下方式实现某些事情

So I want to decode it and encode it in UTF-8, I guess. I understand that something is possible through

import quopri
quopri.decodestring('=A3=E9')

但是后来,我完全迷路了.您将如何对该字符串进行解码/编码以正确打印?

But then, I'm completely lost. How would you do decode/encode this string to get printed properly?

推荐答案

import quopri

编码:

您可以使用quopri.encodestring()将字符'é'编码为Quoted-Printable.它需要一个字节对象,并返回经过QP编码的字节对象.

You can encode the character 'é' to Quoted-Printable using quopri.encodestring(). It takes a bytes object and returns the QP encoded bytes object.

encoded = quopri.encodestring('é'.encode('utf-8'))
print(encoded)

它会打印b'= C3 = A9'(而不是问题中指定的"= AC = E9"或"= A3 = E9")

which prints b'=C3=A9' (but not "=AC=E9" or "=A3=E9" as specified in the question)

解码:

mystring = '=C3=A9'
decoded_string = quopri.decodestring(mystring)
print(decoded_string.decode('utf-8'))

quopri.decodestring()返回一个 bytes 对象,该对象以utf-8编码(可能是您想要的).如果要打印字符'é',请使用.decode()解码 utf-8 编码的字节对象,然后将'utf-8'作为参数传递.

quopri.decodestring() returns a bytes object which is encoded in utf-8(which may be what you want). If you want the character 'é' to be printed, decode utf-8 encoded bytes object using .decode() and pass 'utf-8' as argument.

这篇关于编码问题:在Python中解码带引号的可打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆