Possible Duplicate:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
I am going to skip the part where i tell you how i tested my code and jump straight to the problem.
Python seems to be having some problem matching split of a unicode string to another inline unicode string in an if statement.
>>>zone = u'domain.com.'
>>>zone[-1:]
u'.'
>>>u'.' is u'.' #works fine
True
>>> z[-1:] == u'.' #works fine
True
>>> zone[-1:] is u'.' # FAILS !
False
here is my actual code snippet
>>>if zone[-1:] is not u'.':
>>> #this line will always run !
if i change 'is not' to != the code works fine !
Does anyone know why "is"开发者_JAVA技巧 caused the comparison to fail ?
It's because strings are objects in Python --- when you slice a string, you create a new one.
It's slightly more complicated than that, but that's the gist of it.
Solution: use ==
and !=
instead of is
and is not
.
精彩评论