Hacker News new | ask | show | jobs
by jreese 1476 days ago
This is only true for string literals. Strings constructed at runtime may (and often will) end up as separate objects:

    >>> a = "this is a long sentence in a string literal"
    >>> b = "this is a long" + " sentence in a " + "string literal"
    >>> a is b
    False
    >>> id(a)
    4386376272
    >>> id(b)
    4387721264
    >>> a == b
    True
2 comments

Beware that your method of construction is risky to your demonstration: the python compiler does do some limited optimisations, and trivial constant folding is one of them.

If you test at the shell it apparently misses it (though it works for smaller strings e.g. "abc" / "a" + "b" + "c"), but if you put the same thing in a file and run it, it'll tell you the two strings are identical.

Those two strings aren't equal though, missing some spaces in b :-)
Oops! Thanks for catching that. I fixed the example.