print without intervening space

Alex Martelli aleax at aleax.it
Fri Aug 29 08:05:09 EDT 2003


Ernie wrote:

> Hi,
> 
>>>> for x in range(10)
> ...   print x,
> ...
> 
> will output
> 
> 0 1 2 3 4 5 6 7 8 9
>>>>
> 
> What if somebody wants instead
> 
> 0123456789
> 
> Maybe we need a  printns (print with no spaces) ?

Hopefully not, since you already have several ways to achieve this
purpose ('print' itself is quite redundant, just a convenience):

>>> for x in range(10):
...   print x,
...   sys.stdout.softspace = False
... else:
...   print
...
0123456789
>>>

or, more simply, eschewing print:

>>> for x in range(10):
...   sys.stdout.write(str(x))
... else:
...   sys.stdout.write('\n')
...
0123456789
>>> sys.stdout.writelines([str(x) for x in range(10)]+['\n'])
0123456789
>>> sys.stdout.write(''.join([str(x) for x in range(10)]+['\n']))
0123456789
>>>

Note that the effort in each of these cases to include a
trailing '\n' is just to avoid the interactive interpreter's
prompt overwriting the line we've just printed.


Alex





More information about the Python-list mailing list