print without intervening space

Peter Otten __peter__ at web.de
Fri Aug 29 06:39:49 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) ?

For a list of strings you can do

>>> items = ["a", "b", "c"]
>>> print "".join(items)
abc

Your example would then become

>>> print "".join(map(str, range(10)))
0123456789

which is one of the few occasions where I prefer map() to list
comprehensions. You can then make up a printns() function that comes pretty
close to the requested printns statement.

>>> def printns(*args):
...     print "".join(map(str, args))
...
>>> printns("a", 1)
a1

(If you want stream redirection and a "trailing comma" variant you should
probably write a class with __init__(self, outStream=None, delim=""),
write() and writeln() methods)

By the way, I think that print should have been a function rather than a
statement, but that wish comes definitely too late.

Peter




More information about the Python-list mailing list