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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…