1

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" caused the comparison to fail ?

Community
  • 1
  • 1
guron
  • 23
  • 1
  • 5
  • `is` compares identity, not equality. – Fred Larson Jun 06 '11 at 20:29
  • See http://stackoverflow.com/questions/1150765/a-question-regarding-string-instance-uniqueness-in-python, http://stackoverflow.com/questions/4165688/is-this-a-bug-variables-are-identical-references-to-the-same-string-in-this-exam, and http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs to name but three. – Martijn Pieters Jun 06 '11 at 20:33
  • @MartijnPieters http://stackoverflow.com/questions/4165688/is-this-a-bug-variables-are-identical-references-to-the-same-string-in-this-exam this almost nails it i guess – guron Jun 06 '11 at 21:09

1 Answers1

2

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.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43