开发者

Comparison with unicode string in if-condition (python) [duplicate]

开发者 https://www.devze.com 2023-03-11 21:19 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消