Python – Comparing Two Strings with ‘is’ Not Performing as Expected

pythonstring-comparisonstring-literals

I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:

def uSplit(ustring):
        #return user minus host
        return ustring.split('!',1)[0]

user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
    print 'ok'
else:
    print 'failed'

user = 'theuser'

if user is 'theuser':
    print 'ok'

The output:

type 'str'
theuser
failed
ok

I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use ==, but I'm just curious.

Best Answer

That page you quoted says "If two string literals are equal, they have been put to same memory location" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The is operator can be thought of as a pointer comparison, so two different objects will not compare as identical (even if they contain the same characters, ie. they are equal).

Related Question