Python 字符编码

发布于 2024-09-19 18:18:01 字数 932 浏览 4 评论 0原文

我有以下代码:

msgtxt = "é"

msg = MIMEText(msgtxt)
msg.set_charset('ISO-8859-1')
msg['Subject'] = "subject"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
serv.sendmail("[email protected]","[email protected]", msg.as_string())

电子邮件到达时以 é 作为其正文,而不是

我尝试过的预期 é:

msgtxt = "é".encode("ISO-8859-1")
msgtxt = u"é"
msgtxt = unicode("é", "ISO-8859-1")

所有结果都相同。

如何使这项工作有效?

任何帮助表示赞赏。 预先感谢,J.

I have the following code :

msgtxt = "é"

msg = MIMEText(msgtxt)
msg.set_charset('ISO-8859-1')
msg['Subject'] = "subject"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
serv.sendmail("[email protected]","[email protected]", msg.as_string())

The e-mail arrive with é as its body instead of the expected é

I have tried :

msgtxt = "é".encode("ISO-8859-1")
msgtxt = u"é"
msgtxt = unicode("é", "ISO-8859-1")

all yield the same result.

How to make this work?

Any help is appreciated.
Thanks in advance, J.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浊酒尽余欢 2024-09-26 18:18:01
msgtxt = "é"
msg.set_charset('ISO-8859-1')

那么,包含此代码的源文件的编码是什么?如果它是 UTF-8(这是一个很好的默认选择),只需编写 é 就会得到两字节字符串 '\xc3\xa9',当被视为 ISO-8859-1,看起来像 é

如果您想在源文件中使用非 ASCII 字节字符串文字,而不必担心文本编辑器将其保存为什么编码,请使用字符串文字转义:

msgtxt = '\xE9'
msgtxt = "é"
msg.set_charset('ISO-8859-1')

Well, what's the encoding of the source file containing this code? If it's UTF-8, which is a good default choice, just writing the é will have given you the two-byte string '\xc3\xa9', which, when viewed as ISO-8859-1, looks like é.

If you want to use non-ASCII byte string literals in your source file without having to worry about what encoding the text editor is saving it as, use a string literal escape:

msgtxt = '\xE9'
冰雪梦之恋 2024-09-26 18:18:01
# coding: utf-8        (or whatever you want to save your source file in)
msgtxt = u"é"
msg = MIMEText(msgtxt,_charset='ISO-8859-1')

如果没有 u,文本将采用源编码。作为 Unicode 字符串,msgtxt 将使用指定的字符集进行编码。

# coding: utf-8        (or whatever you want to save your source file in)
msgtxt = u"é"
msg = MIMEText(msgtxt,_charset='ISO-8859-1')

Without the u the text will be in the source encoding. As a Unicode string, msgtxt will be encoded in the indicated character set.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文