How to stop print printing spaces?

CC crobc at
Sun Jul 29 04:56:13 CEST 2007

Roel Schroeven wrote:
> CC schreef:
>> ln = '\x00\x01\xFF 456789abcdef'
>> # This works:
>> import sys
>> for i in range(0,15):
>>      sys.stdout.write( '%.2X' % ord(ln[i]) )
>> print
>> Is that the best way, to work directly on the stdout stream?
> It's not a bad idea: print is mostly designed to be used in interactive 
> mode and for quick and dirty logging; not really for normal program 
> output (though I often use it for that purpose).
> There is another way: construct the full output string before printing 
> it. You can do that efficiently using a list comprehension and the 
> string method join():
>  >>> print ''.join(['%.2X' % ord(c) for c in ln])
> 0001FF20343536373839616263646566

Oh yeah, that's right!

> In Python 2.4 and higher, you can use a generator expression instead of 
> a list comprehension:
>  >>> print ''.join('%.2X' % ord(c) for c in ln)
> 0001FF20343536373839616263646566

Hmm.  I'm at 2.3 :-(

> BTW, in your examples it's more pythonic not to use range with an index 
> variable in the for-loop; you can loop directly over the contents of ln 
> like this:
> import sys
> for c in ln:
>     sys.stdout.write('%.2X' % ord(c))
> print

Ah yes, duh!  I played with this means of iterating over items in a 
sequence the other day while studying the tutorial, but it sinks in 
slowly for a C programmer.

That's why I posted my silly code.  I'll probably do that a lot until I 
get used to this pythonic business.

Thanks for the input!

Christopher R. Carlen
crobc at
SuSE 9.1 Linux 2.6.5

More information about the Python-list mailing list