Comparing two lines with "is" - not performed as expected

I am trying to compare two lines with . One line is returned by the function, and the other is simply specified by comparison. - these are tests for identifying an object, but according to this page , it also works with two identical strings due to Python memory optimization. But the following does not 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' 

Exit:

  type 'str'
 theuser
 failed
 ok 

I assume the reason is that the string returned by the function is a different "type" of the string than the string literal. Is there a way to get a function to return a string literal? I know I can use == , but I'm just curious.

+1
python string-literals string-comparison
Aug 01 '09 at 9:44
source share
3 answers

The site you are quoting says the following:

If two string literals are equal, they are placed in one memory cell.

But

 uSplit('theuser!host') 

not a string literal - this is the result of the operation on the literal 'theuser!host' .

In any case, you usually shouldn't check for string equality with is , because this memory optimization is just the implementation detail you shouldn't rely on anyway.




In addition, you should use is for things like is None . Use it to check if the two objects — the classes you created — are the same instance. You cannot easily use it for strings or numbers, because the rules for creating these built-in classes are complex. Some lines are interned. Some rooms are likewise interned.

+2
Aug 01 '09 at 9:51
source share

This page that you indicated says: "If two lines of literals are equal, they are placed in the same memory location" (my selection). Python puts string literals, but the strings returned from some arbitrary function are separate objects. The is operator can be considered as a comparison of pointers, so two different objects will not be compared as identical (even if they contain the same characters, i.e. they are equal).

+3
Aug 01 '09 at 9:50
source share

What did you come across that Python doesn't always put all its lines. More details here:

http://mail.python.org/pipermail/tutor/2009-July/070157.html

0
Aug 01 '09 at 9:52
source share



All Articles