removing spaces when mixing variables / text

Mike C. Fletcher mcfletch at rogers.com
Tue Feb 3 03:32:14 EST 2004


tgiles wrote:
...

>	print a,".",b,".",c,".",d	
>	n = n-1
>
>The output at the moment looks like so:
>
>179 . 72 . 138 . 272
>21 . 124 . 83 . 9
>
>When, in a perfect universe it would look like so:
>
>179.72.138.272
>21.124.83.9
>  
>
print is a convenience used to do quick-and-dirty output.  It's focused 
on that convenience rather than on pretty formatting of reports.  So, if 
you're into the Java way of doing things:

import sys
sys.stdout.write( repr(a))
sys.stdout.write( '.' )
sys.stdout.write( repr(b))
...

Or, you could use one of these common idioms:

    # construct a string with the entire representation before printing
    print ".".join( [ str(x) for x in (a,b,c,d) ] )
    # or
    print str(a)+'.'+str(b)+'.'+str(c)+'.'+str(d)
    # or
    print '%(a)s.%(b)s.%(c)s.%(d)s'%locals()
    # or
    print '%s.%s.%s.%s' % (a,b,c,d)

String formatting (seen in those last two examples) is a very powerful 
mechanism, more focused on less regular formatting tasks, while the 
first example is more appropriate for tasks processing very large 
quantities of regular data.  The simple addition of strings is fine for 
very simple code, but tends to get a little clumsy eventually.

Welcome to the perfect universe :) ,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list