关于在2.7中出现 "UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode

Posted 清源居士

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于在2.7中出现 "UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode相关的知识,希望对你有一定的参考价值。

在中文字符串前面加u. 

 

Make sure your code is in UTF-8 (NOT Latin-1) and/or use a coding line as so:

#! /usr/bin/python
# -*- coding: utf-8 -*-
a = {"a": u"??"}
b = "??"
assert b == a[a]
assert b.decode(utf-8) == a[a].decode(utf-8)

 

If you‘re using unicode across the board, you can import unicode_literals from the future and cut back on encoding heartaches:

#! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
a = {"a": u"??"}
b = "??"
assert b == a[a]
assert b == a[a]
assert b.encode(utf-8) != a[a]
assert b.encode(utf-8) == a[a].encode(utf-8)

 

If a file uses unicode_literals, all "strings" are now u"unicode" objects (per the coding of the file) if they‘re not b"prepended" with a b (to emulate the string/bytes split in Python 3.X).

 

以上是关于关于在2.7中出现 "UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode的主要内容,如果未能解决你的问题,请参考以下文章

在 Python 2.7 中检查字符串“None”或“not”

python 2.7小写

关于项目在网页中运行部分jsp出现乱码(由request.getRequestDispatcher("XXX.jsp").forward(request, response)造成)

在 CMD 中“python”启动 Python 3.3,“py”启动 Python 2.7,我该如何更改?

关于Python字典的两道题目

使用 Twilio + Flask + Ngrok + Python (2.7) 在本地主机上出现 404 错误