How to stop print printing spaces?

Roel Schroeven rschroev_nospam_ml at
Sun Jul 29 00:57:01 CEST 2007

CC schreef:
> Hi:
> I've conjured up the idea of building a hex line editor as a first real 
> Python programming exercise.
> To begin figuring out how to display a line of data as two-digit hex 
> bytes, I created a hunk of data then printed it:
> ln = '\x00\x01\xFF 456789abcdef'
> for i in range(0,15):
>      print '%.2X ' % ord(ln[i]),
> This prints:
> 00  01  FF  20  34  35  36  37  38  39  61  62  63  64  65
> because print adds a space after each invocation.
> I only want one space, which I get if I omit the space in the format 
> string above.  But this is annoying, since print is doing more than what 
> I tell it to do.
> What if I wanted no spaces at all?  Then I'd have to do something 
> obnoxious like:
> for i in range(0,15):
>      print '\x08%.2X' % ord(ln[i]),
> 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])

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)

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))

If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

More information about the Python-list mailing list