Python:从 ISO-8859-1/latin1 转换为 UTF-8

Python: Converting from ISO-8859-1/latin1 to UTF-8(Python:从 ISO-8859-1/latin1 转换为 UTF-8)

本文介绍了Python:从 ISO-8859-1/latin1 转换为 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用电子邮件模块将这个字符串从 Quoted-printable 解码为 ISO-8859-1.这给了我像xC4pple"这样的字符串,它对应于Äpple"(瑞典语中的Apple).但是,我无法将这些字符串转换为 UTF-8.

<预><代码>>>>苹果 = "xC4pple">>>苹果'xc4pple'>>>苹果编码(UTF-8")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xc4:序号不在范围内 (128)

我该怎么办?

解决方案

先解码再编码:

apple.decode('iso-8859-1').encode('utf8')

I have this string that has been decoded from Quoted-printable to ISO-8859-1 with the email module. This gives me strings like "xC4pple" which would correspond to "Äpple" (Apple in Swedish). However, I can't convert those strings to UTF-8.

>>> apple = "xC4pple"
>>> apple
'xc4pple'
>>> apple.encode("UTF-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in     range(128)

What should I do?

解决方案

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

这篇关于Python:从 ISO-8859-1/latin1 转换为 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Python:从 ISO-8859-1/latin1 转换为 UTF-8

基础教程推荐