【问题标题】:Formatting a non english string格式化非英文字符串
【发布时间】: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


【解决方案1】:
def postWP(gameTitle,gameCode):
    # additional parameter checking
    if not isinstance(gameTitle, basestring):
        print "gameTitle type error"
        return
    if not isinstance(gameCode, basestring):
        print "gameCode type error"
        return
    if isinstance(gameTitle, unicode):
        gameTitle = gameTitle.encode('utf8')
    if isinstance(gameCode, unicode):
        gameCode = gameCode.encode('utf8')

    # the following remains the same
    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()

【讨论】:

  • 还是不行。 PostWP activated, Title: ╫ש╫ץ╫ñ╫ש ╫₧╫ó╫ש╫ף╫ƒ ╫פ╫נ╫ס╫ƒ Error: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)
  • 失败时能把gameTitle和gameCode贴出来吗?
  • 例如当 gameTitle="מייפל סטורי" and gameCode='example.com/media/528g1a3f51341Maple-Story-SV3.swf" width="800" height= "600">'
  • 由于这里的gameCode不是basestring的实例,要么是str要么是unicode,所以应该打印“gameCode type error”并返回。你真的用这些输入运行程序吗?
  • 是的,我是.. 使用您编写的代码时出现以下错误:Error: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) Error: Traceback (most recent call last): File "girlgames.py", line 124, in <module> print "Error: ", format(er) UnicodeEncodeError: 'ascii' codec can't encode characters in position 86-89: ordinal not in range(128)
猜你喜欢
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 2010-10-03
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多