Controlling output using print with format string

Bengt Richter bokr at oz.net
Sun Oct 30 20:09:43 EST 2005


On Sun, 30 Oct 2005 18:44:06 -0600, Paul Watson <pwatson at redlinepy.com> wrote:

>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?
>
Maybe. But I wouldn't say "uncontrollable" -- print is pretty predictable.

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

If you like C, you can make something pretty close to printf:

 >>> import sys
 >>> def printf(fmt, *args):
 ...     s = fmt%args
 ...     sys.stdout.write(s)
 ...     return len(s)
 ...
 >>> s = 'now is the time'
 >>> for c in s:
 ...     printf('%s', c)
 ...
 n1
 o1
 w1
  1
 i1
 s1
  1
 t1
 h1
 e1
  1
 t1
 i1
 m1
 e1

Oops, interactively you probably  want to do something other
than implicity print the printf return value ;-)

 >>> s = 'now is the time'
 >>> for c in s:
 ...     nc = printf('%s', c)
 ...
 now is the time>>>
 >>> for c in s:
 ...     nc = printf('%c', c)
 ...
 now is the time>>>
 >>> for c in s:
 ...     nc = printf('%1c', c)
 ...
 now is the time>>>
 
Just to show multiple args, you could pass all the characters
separately, but at once, e.g., (of course you need a format to match)

 >>> printf('%s'*len(s)+'\n', *s)
 now is the time
 16

 >>> printf('%s .. %s .. %s .. %s\n', *s.split())
 now .. is .. the .. time
 25

Or just don't return anything (None by default) from printf if you
just want to use it interactively. Whatever.

Your character-by-character output loop doesn't give much of a clue
to what obstacle you are really encountering ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list