字符串中的Python特殊字符 [英] Python special characters in Strings

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

问题描述

我想在网页中显示电子邮件。该程序是用Python编写的。不幸的是,我有一些字符编码问题。

I am trying to show email within a webpage. The program is written in Python. Unfortunately, I have some character encoding issues. I have quotes and double quotes in the text.

原始邮件:

"All is good"
‘it is getting better’

windows-1252'我从ISP获得:

with character set 'windows-1252' I get from the ISP:

=93All is good=94
=91it is getting better=92

与字符集'utf-8'我从ISP获得:

with character set 'utf-8' I get from the ISP:

=E2=80=9CAll is good=E2=80=9D
=E2=80=98it is getting better=E2=80=99

我替换了 = .. 它们相应的十六进制字符。文字如下:

I replace the =.. with their corresponding hex characters. The text then looks like:

character set 'windows-1252'
ôAll is goodö
æit is getting betterÆ


character set 'utf-8'
ΓÇ£All is goodΓÇ¥
ΓÇÿit is getting betterΓÇÖ

后续调用unicode函数失败,

Subsequent calls to the unicode function fail with

UnicodeEncodeError: 'charmap' codec can't encode character u'\u201d' in position 6: 
character maps to <undefined>

或类似。

unicode(message,'utf-8','replace')
任何想法我做错了什么?

The call looks like unicode( message, 'utf-8', 'replace' ). Any idea what I am doing wrong?

推荐答案

为什么要用任何东西替换任何东西?

Why are you replacing anything with anything?

>>> m = email.message_from_string('''Content-Type: text/plain; utf-8\nContent-Transfer-Encoding: quoted-printable\n\n=E2=80=9CAll is good=E2=80=9D\n=E2=80=98it is getting better=E2=80=99''')
>>> m.get_payload(decode=True).decode(m['Content-Type'].split('; ')[1])u'\u201cAll is good\u201d\n\u2018it is getting better\u2019'

这篇关于字符串中的Python特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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