Is there any difference between print 3 and print '3' in Python ?

Robert Kern robert.kern at gmail.com
Mon Mar 26 08:10:55 EDT 2012


On 3/26/12 12:45 PM, redstone-cold at 163.com wrote:
> I know the print statement produces the same result when both of these two instructions are executed ,I just want to know Is there any difference between print 3 and print '3' in Python ?

Yes, there is a difference, but not much.

[~]
|6> import dis

[~]
|7> dis.disassemble(compile('print 3', '<string>', 'exec'))
   1           0 LOAD_CONST               0 (3)
               3 PRINT_ITEM
               4 PRINT_NEWLINE
               5 LOAD_CONST               1 (None)
               8 RETURN_VALUE

[~]
|8> dis.disassemble(compile('print "3"', '<string>', 'exec'))
   1           0 LOAD_CONST               0 ('3')
               3 PRINT_ITEM
               4 PRINT_NEWLINE
               5 LOAD_CONST               1 (None)
               8 RETURN_VALUE


As you can see, the only difference is in the first instruction. Both of these 
put the object that you specified by the literal onto the stack. The difference 
is that one is the int object specified by the literal 3 and the other is the 
str object specified by the literal "3". Both of these objects happen to give 
the same __str__ output, so that's what gets printed.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list