[Tutor] re. printing

Charlie Clark charlie@begeistert.org
Sat Feb 15 06:48:01 2003


On 2003-02-14 at 23:31:13 [+0100], tutor-request@python.org wrote:
> >>>x=['h','e','l','l','o']
> >>>for i in range(0, len(x)):
... 
> >h e l l o
...
 
> If you need more fine-grained control of output than you can get from 
> print, then use sys.stdout.write().
> 
>  >>> import sys
>  >>> for x in ['h', 'e', 'l', 'l', 'o']:
> ...     sys.stdout.write(x)
> ...
> hello

I'm not going to argue with Jeff on this but I'm not sure if the solution 
is really appropriate. But I would point out his implicit correction of 
your loop. Being able loop directly over sequences is a really nice thing 
in Python.

We always print strings or string representations of objects, bearing that 
in mind it often makes more sense to convert objects explicitly into 
strings before printing them.

The archetypal conversion of a list to a string is by using the join() 
method of string objects. The syntax takes a while to get used to because 
you apply the method to a separator (any kind of string even an empty one) 
and pass it a sequence as a paramter.

>>> print "".join(x)
will give you what you want

You can also make use of substitution for greater control

>>> print "first half '%s%s%s' second half '%s%s'" %tuple(x)
first half 'hel' second half 'lo'

I'll leave it to the gurus to explain why you have to convert the list to a 
tuple to do the substitution / string formatting. I think string 
substitution is actually something else using the evil $ and is staring us 
in the face in the form of future Python versions

Charlie