[英]Converting Unicode string to ascii string, then comparing it to an ascii string always returns false. (Python 2.7.6)
This seems like a simple question, but I can't find an answer anywhere. 这似乎是一个简单的问题,但我在任何地方都找不到答案。
I have a function that gets a Unicode string as an argument, and looks like this: 我有一个将Unicode字符串作为参数的函数,如下所示:
def foo(arg):
if str(arg) is 'wxyz':
print 'it is equal'
Given the input u'wxyz', the function doesn't print anything. 给定输入u'wxyz',该函数不会打印任何内容。 I did some more testing and I have come up with a question. 我做了一些测试,然后提出了一个问题。
Why does this not work: 为什么这不起作用:
>>> u = unicode('wxyz')
>>> str(u) is 'wxyz'
False
But this does work: 但这确实有效:
>>> str(u) == 'wxyz'
True
Here's what I have tried already: 这是我已经尝试过的方法:
>>> u = unicode('wxyz')
>>> s = str(u)
>>> a = u.encode('ascii')
>>> type(u)
<type 'unicode'>
>>> type(s)
<type 'str'>
>>> type(a)
<type 'str'>
>>> type('wxyz')
<type 'str'>
>>> u is 'wxyz'
False # Should be False
>>> u == 'wxyz'
False # Should be False
>>> s is 'wxyz'
False # Should be True
>>> s == 'wxyz'
True # Should be True
>>> a is 'wxyz'
False # Should be True
>>> a == 'wxyz'
True # Should be True
>>> u is u'wxyz'
False # Should be True
>>> u == u'wxyz'
True # Should be True
I guess that I could change the 'is' to a '==', but I've been using 'is' everywhere else in the code, and it doesn't seem very Python-esque to switch to using '=='. 我想我可以将'is'更改为'==',但是我一直在代码中的其他所有地方使用'is',并且切换到使用'=='似乎不太像Python 。 If someone could help me understand this, I would be very appreciative. 如果有人可以帮助我理解这一点,我将不胜感激。 Also, if you need me to be more specific, please ask. 另外,如果您需要我提供更多具体信息,请询问。
I seriously apologize if this has been asked anywhere else. 如有其他要求,我深表歉意。 I read the Python documentation on Unicode and looked for similar questions here, but I couldn't find anything that answered my question. 我阅读了有关Unicode的Python文档,并在此处查找了类似的问题,但找不到任何能回答我问题的内容。
The operator a is b
returns True if a and b are bound to the same object . 如果a和b 绑定到同一对象,则a is b
的运算符返回True。 So is
is the wrong operator to be using here. 所以, is
要在这里使用了错误的操作。 That probably means you need to fix most places you've used is
in your code. 这可能意味着你需要解决您最常用的地方is
在你的代码。
a = []
b = a
a is b # true
a == b # true
a = []
b = []
a is b # false
a == b # true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.