【发布时间】:2018-01-28 20:13:06
【问题描述】:
我编写了一个函数,它需要格式化包含希伯来字母的字符串,该脚本在使用英文字母时可以完美运行。但是当使用希伯来语时,它给了我以下错误:
错误是:
Error: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
功能代码是(define行下的代码是缩进的,不像代码块中看到的那样):
def postWP(gameTitle,gameCode):
print "PostWP activated, Title: %s" % gameTitle
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('email@gmail.com','emailPassword')
message = 'Subject: {}\n\n{}'.format(gameTitle, gameCode)
print "Sending mail..."
mail.sendmail('email@gmail.com','destination@mail.com',message)
mail.close()
基本上,问题出现在'Subject: {}\n\n{}'.format(gameTitle, gameCode)'。
我想知道如何修复它。提前感谢所有试图提供帮助的人! 最好的问候,祝你有美好的一天!
【问题讨论】:
-
只需使用
unicode格式字符串:message = u'Subject: {}\n\n{}'.format(gameTitle, gameCode)(注意u)。更好的是,切换到 Python3,您就不必担心 Unicode 字符串了。 -
你试过把以下内容放在文件的开头吗? # -*- 编码:utf8 -*-
-
如果你不使用 Python 的电子邮件处理模块,你会发现很难做到这一点。
-
@JackYang 是的,我已经在文件开头写了,谢谢。
标签: python python-2.7