如何解决UnicodeWarning问题? [英] How do I solve the UnicodeWarning issue?

查看:145
本文介绍了如何解决UnicodeWarning问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了大约四个小时研究"Unicode警告:Unicode不相等比较"问题.通常,几个小时后,我就能自己回答最棘手的问题,但事实并非如此.当然,我对自己来说是棘手". ;-)

I spent about four hours researching the "UnicodeWarning: Unicode unequal comparison" issue. Usually, after a few hours, I'm able to answer my trickiest questions by myself, but that wasn't the case here. And I mean "tricky" for myself, of course. ;-)

我知道在线上和也在此站点上都回答了类似的问题,但是过于笨拙而无法很好地理解答案对我完全没有帮助.也许对我而言,最好的方法就是让别人指出我的代码中需要更改的内容.

I know that similar questions are answered online and also on this site, but being too noob to understand the answer well doesn't help me at all. Maybe the best way for me to get it is just having someone point out what needs to be changed in my code.

我在Windows XP上使用Python 2.5.

I use Python 2.5 on Windows XP.

我能弄清的东西

我了解我的问题与尝试比较苹果和橙子(或Unicode和ASCII,或类似的东西,例如字节)有关.我不知道是解决此问题的实用方法.

I understand that my problem has to do with me trying to compare apple and oranges (or Unicode and ASCII, or something like that, like maybe bytes). What I don't know is a practical way to solve this.

这是我的代码:

# coding: iso-8859-1
import sys
from easygui import *

actual_answer = "pureté"
answer_given = enterbox("Type your answer!\n\nHint: 'pureté'")

if answer_given == actual_answer:
    msgbox("Correct! The answer is 'pureté'")
else:
    msgbox("Bug!")

这是我收到的错误消息:

Unicode警告:Unicode相等比较无法将两者转换 Unicode参数-解释为不相等

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

推荐答案

首先,请阅读以下内容: http ://www.joelonsoftware.com/articles/Unicode.html

First, read this: http://www.joelonsoftware.com/articles/Unicode.html

然后-在任何系统中处理Python时,您都不应该真正使用iso-8859-1编码-而是使用utf-8.

Then - you should not really use iso-8859-1 encoding when dealing with Python in whatever system - use utf-8 instead.

第三,您的easygui组件将为您返回一个unicode对象,而不是字节字符串.解决上面代码中最简单的方法是使actual_answer变量成为unicode对象,但在引号前加上"u",例如:

Third, your easygui component is returning you a unicode object instead of a byte-string. The easiest way to fix that in the above code is to make the actual_answer variable an unicode object, but prefixing an "u" to the quotes, like in:

actual_answer = u"pureté"

这篇关于如何解决UnicodeWarning问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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