Is there any difference between print 3 and print '3' in Python ?
J. Cliff Dyer
jcd at sdf.lonestar.org
Mon Mar 26 19:06:58 CEST 2012
As others have pointed out, the output is the same, because the result
of converting an integer to a string is the string of that integer.
However, other numeric literals might not do what you want, due to the
fact that they are converted to an internal numeric representation, then
converted back to a string in a canonical format.
>>> print 3, '3'
>>> print 3.00, '3.00'
>>> print 0x3, '0x3'
>>> print 03, '03'
>>> print 3e0, '3e0'
You might think that the take away message is to use the string
representation, since it prints what you tell it to print. However, if
you use a number, you can specify the output formatting with more
fine-grained control, and even exert that control on calculated number:
>>> print '%0.2f' % (3,)
>>> print '%0.2f' % (2 + 1)
This is better because you can't perform math on a string:
>>> print '2' + '1'
>>> print '2.00' + '1.00'
print '2 + 1'
2 + 1
So in general, you should use numbers, and then format them using
standard string formatting operations when you want to print them.
There's more information on how to do formatting here:
On Mon, 2012-03-26 at 04:45 -0700, 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 ?
More information about the Python-list