Controlling output using print with format string

Mike Meyer mwm at mired.org
Sun Oct 30 20:37:14 EST 2005


Paul Watson <pwatson at redlinepy.com> writes:

> It is clear that just using 'print' with variable names is relatively
> uncontrollable.  However, I thought that using a format string would
> reign the problem in and give the desired output.
>
> Must I resort to sys.stdout.write() to control output?

No. You can control the output of print to whatever degree you want -
just convert the printed objects to strings by hand before printing
them.

> $ python
> Python 2.4.1 (#1, Jul 19 2005, 14:16:43)
> [GCC 4.0.0 20050519 (Red Hat 4.0.0-8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> s = 'now is the time'
>  >>> for c in s:
> ...     print c,
> ...
> n o w   i s   t h e   t i m e
>  >>> for c in s:
> ...     print "%c" % (c),
> ...
> n o w   i s   t h e   t i m e
>  >>> for c in s:
> ...     print "%1c" % (c),
> ...
> n o w   i s   t h e   t i m e

On the other hand, you can't keep print from putting a space between
all the objects it prints. So you have to convert all the objects into
a single string before printing that string.

     <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list