As already noted, this should always be true for strings created in python (or CPython, anyway), but if you use the C extension, it won't.
As a quick counter example:
import numpy as np x = 's' y = np.array(['s'], dtype='|S1') print x print y[0] print 'x is y[0] -->', x is y[0] print 'x == y[0] -->', x == y[0]
This gives:
s s x is y[0] --> False x == y[0] --> True
Of course, if nothing had ever used any C extension, you would probably be safe ... I would not count on it, though ...
Edit: as an even simpler example, it fails if everything was pickled or packed with struct any way.
eg:.
import pickle x = 's' pickle.dump(x, file('test', 'w')) y = pickle.load(file('test', 'r')) print x is y print x == y
Also (for clarity, use a different letter, since we need "s" for the format string):
import struct x = 'a' y = struct.pack('s', x) print x is y print x == y
source share