how to print without blank?

Rick Zantow rzantow at gmail.com
Sun Apr 9 10:36:14 EDT 2006


Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote in
news:pan.2006.04.09.07.02.28.116455 at REMOVETHIScyber.com.au: 

> On Sat, 08 Apr 2006 22:54:17 -0700, Ju Hui wrote:
> 
>> I want to print 3 numbers without blank.
> [snip]
>> how to print
>> 012
>> ?
> 
> Method one: accumulate your numbers into a single string, then print
> it in one go.
> 
>>>> L = []
>>>> for x in range(3):
> ...     L.append(str(x))
> ... 
>>>> print ''.join(L)
> 012
>>>> 
> 
> 
> Or even:
> 
>>>> print ''.join(map(str, range(3)))
> 012
>>>> 
> 
> 
> Or use a list comprehension:
> 
>>>> print ''.join([str(x) for x in range(3)])
> 012
>>>> 
> 
> 
> 
> Method two: don't use the print statement, but write directly to
> standard output.
> 
>>>> import sys
>>>> for x in range(3):
> ...     sys.stdout.write(str(x))
> ...
> 012>>>
> 
> 
> But notice how this does not write a newline when you are done -- you
> will have to remember to do it yourself with sys.stdout.write('\n').
> 
> Also, print will work with any object, but sys.stdout.write will only
> work with strings:
> 
>>>> print 6
> 6
>>>> sys.stdout.write(6)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: argument 1 must be string or read-only character buffer,
> not int 
>>>>
> 
> 
> 

Although the sysout.write() approach is (IMHO) the best, for the OP's 
case, he could try method three:

for x in range(3):
    print '\b%d' % x,

-- 
rzed



More information about the Python-list mailing list