Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print format? which one is better python

Tags:

python

I have always been curious

Why does python have different way to print stuff?

for example

print "this is ",a," and " ,b

vs

print "this is %d and %d" %(a,b)

Any performance issues? and stuff?

like image 634
frazman Avatar asked Apr 14 '26 09:04

frazman


2 Answers

There are many more ways to "print stuff" in Python, too, including the more modern str.format() approach, sys.stdout.write('foo'), and probably others.

In terms of the difference between print a, b, c and % formatting, I generally use the former mostly for debugging output, when you just want spaces between a bunch of variables. When I want exact formatting or more control over the formatting, I use % (actually, these days I always use str.format).

For example:

print 'DEBUG:', var1, var2

Versus:

print 'Benchmarks took {0:.3f}s to run'.format(seconds)

Also, % and str.format formatting are much more general -- they don't actually print anything, they return a string, which you can print, write to a file, store in a database, send as a web response, etc.

Regarding performance -- just don't worry about it. All three are almost certainly fast, and premature optimization is the root of all evil.

I don't really want to post numbers (as that may encourage the wrong mindset), but timeit is so simple to use I couldn't help myself.

C:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
                     "print >>s, 'this is', 'a', 'test'"
100000 loops, best of 3: 3.39 usec per loop

c:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
                     "print >>s, 'this is %s test' % 'a'"
1000000 loops, best of 3: 1.32 usec per loop

C:\>python -m timeit -s "import cStringIO; s = cStringIO.StringIO()"
                     "print >>s, 'this is {0} test'.format('a')"
1000000 loops, best of 3: 1.64 usec per loop

I'm not quite sure why the print a, b, c approach is significantly slower, probably an implementation detail. But still, don't worry about it -- the time it takes to print to your file or screen probably far outweighs the string formatting part.

like image 87
Ben Hoyt Avatar answered Apr 16 '26 22:04

Ben Hoyt


The second method allows better formatting of your printed arguments. For example, you can specify to format a number as hexadecimal, or specify a number of decimals to be displayed of a floating point number.

like image 20
Hans Then Avatar answered Apr 16 '26 22:04

Hans Then



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!