next up previous contents
Next: Referencing Variables By Up: The Formatting Operator Previous: The Formatting Operator

Basic Usage

The chapter on output formatting is really out of date: there is now an almost complete interface to C-style printf formats. This is done by overloading the modulo operator (%) for a left operand which is a string, e.g.

        >>> import math
        >>> print 'The value of PI is approximately %5.3f.' % math.pi
        The value of PI is approximately 3.142.
        >>>

If there is more than one format in the string you pass a tuple as right operand, e.g.

        >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
        >>> for name, phone in table.items():
        ...     print '%-10s ==> %10d' % (name, phone)
        ... 
        Jack       ==>       4098
        Dcab       ==>    8637678
        Sjoerd     ==>       4127
        >>>

Most formats work exactly as in C and require that you pass the proper type (however, if you don't you get an exception, not a core dump). The %s format is more relaxed: if the corresponding argument is not a string object, it is converted to string using the str() built-in function. Using * to pass the width or precision in as a separate (integer) argument is supported. The C formats %n and %p are not supported.



guido@cwi.nl