-2

Hoping someone can explain the following discrepancy:

>>> s1 = "Cyber security"
>>> s2 = "Cyber security"
>>> id(s1) == id(s1)
True
>>> id(s1) == id(s2)
False
>>> s1 = "cyber"
>>> s2 = "cyber"
>>> id(s1) == id(s2)
True
>>> s2 = "cyber "
>>> s2 = "cyber "
>>> id(s1) == id(s2)
False

Why does the space make the id() False, yet different variables with no spaces are True?

Dannellyz
  • 31
  • 2
  • Note: while you'd have seen the same effect regardless, your transcript doesn't show what you want it to, because you don't change `s1` in the last group.. so you're comparing `"cyber"` with `"cyber "`. – DSM Nov 01 '13 at 15:44

1 Answers1

0

From the Python documentation of id():

This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

There is absolutely no guarantee two objects will have the same id, in fact the opposite is guaranteed.

If you want to compare strings, compare them directly.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123