pre-PEP: Print Without Intervening Space

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 11 09:31:23 EST 2005


Marcin Ciura wrote:

>      None of the more efficient solutions is particularly
>      straightforward, either:
> 
>          result = []
>          for x in seq:
>              result.append(fn(x))
>          print ''.join(result)
> 
>          print ''.join([fn(x) for x in seq])
> 
>          print ''.join(fn(x) for x in seq)
> 
>      Moreover, all of them require creating one or two temporary
>      objects to hold the entire result.  If the programmers use one of
>      them without qualms, it is only because their mind is warped by
>      the limitation of print.

I can't say I lose much sleep over this, but you could add my preferred 
workaround to the list (I don't believe it suffers from the same drawbacks 
as the options you propose) and say why your comma solution is better than 
it:

import sys
def nospace(value, stream=None):
    '''Suppress output of space before printing value'''
    stream = stream or sys.stdout
    stream.softspace = 0
    return str(value)

>>> print "a", nospace("b")
ab
>>> def fn(x):
	return "<%s>" % x

>>> for i in range(10):
	print nospace(fn(i)),

	
<0><1><2><3><4><5><6><7><8><9>




More information about the Python-list mailing list