views:

115

answers:

3
var1 = 'abc'
var2 = 'xyz'

print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz

... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?

Thanks

A: 

Using a comma gives the print function multiple arguments (which in this case are printed all, seperated by a space. Using the plus will create one argument for print, which is printed in its entirety. I think using the + is best in this case.

Lex
+3  A: 

Passing strings as arguments to print joins them with the 'sep' keyword. Default is ' ' (space).

Separator keyword is Python 3.x only. Before that the separator is always a space, except in 2.5(?) and up where you can from __future__ import print_function or something like that.

>>> print('one', 'two') # default ' '
one two
>>> print('one', 'two', sep=' and a ')
one and a two
>>> ' '.join(['one', 'two'])
one two
>>> print('one' + 'two')
onetwo
Tor Valamo
which is the fastest among the two?
Nimbuz
+4  A: 
Roger Pate
which is the fastest among the two?
Nimbuz
They do different things, you cannot reasonably compare them for speed. That said, you can compare *printing* the two different ways, use the timeit module.
Roger Pate