设置非英语字符串的格式



我编写了一个函数,该函数需要格式化包含希伯来字母的字符串,该脚本在使用英语字母时可以完美运行。但是当使用希伯来语时,它会给我以下错误:

错误是:

Error:  'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

函数代码为(定义行下的代码是缩进的,而不是代码块中所示(:

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: {}nn{}'.format(gameTitle, gameCode)
print "Sending mail..."
mail.sendmail('email@gmail.com','destination@mail.com',message)
mail.close()

基本上,问题发生在'Subject: {}nn{}'.format(gameTitle, gameCode)'.

我想知道如何修复它。提前感谢所有试图提供帮助的人! 最好的问候,祝你有美好的一天!

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: {}nn{}'.format(gameTitle, gameCode)
print "Sending mail..."
mail.sendmail('email@gmail.com','destination@mail.com',message)
mail.close()

最新更新