如何比较两个非ASCII字符串

raj*_*aju 0 python unicode ascii python-2.7

我想Technical Diploma (±12 years)与浏览器中显示的相同字符串进行比较.我在Python中运行webdriver测试,它Technical Diploma (±12 years)从数据库中获取并尝试与浏览器中的字符串进行比较.我尝试比较时收到此错误

UnicodeWarning:Unicode相等比较无法将两个参数都转换为Unicode - 将它们解释为不相等

如何在Python中比较这些非ASCII字符串?

Mar*_*ers 6

您的一个字符串不是unicode值,而是bytestring.您想通过首先解码它将其转换为unicode:

'Non-ASCII value containing UTF8: \xc2\xb1'.decode('utf8')
Run Code Online (Sandbox Code Playgroud)

但是你必须首先弄清楚bytestring的编码方式.

如果已定义源文件编码,并且在代码中将字符串定义为文字,请确保通过在字符串前面添加以下内容将其定义为Unicode文字u'':

u'Technical Diploma (±12 years)'
Run Code Online (Sandbox Code Playgroud)

不过,我强烈建议您在继续之前阅读Python Unicode HOWTO.