------------------------------------------------------------------------------
MC logo
Output Formatting
[^] Code Examples
------------------------------------------------------------------------------
<<Sorting io.py Reading Files>>
#!/usr/bin/python3

import random

# Using the back ticks, which convert to string.
for n in range(0,5):
    a = random.randrange(0, 101)
    b = random.randrange(0, 201)
    print(str(a) + '+' + str(b), '=', str(a+b))
print()

# Using the % operator, similar to printf.
for n in range(0,5):
    a = random.randrange(0, 101)
    b = random.randrange(0, 201)
    print('%d+%d = %d' % (a, b, a + b))
print()

# % allows field sizes as well.
for n in range(0,5):
    a = random.randrange(-100, 101)
    b = random.randrange(-50, 201)
    print('%4d + %4d = %4d' % (a, b, a + b))
print()

# Some other formatting.
dribble = { 'onion' : 1.4,
            'squash' : 2.02,
            'carrots' : 1.0,
            'pixie toenails' : 43.22,
            'lemon drops' : .75 }
for n in dribble:
    print('%-15s %6.2f' % (n + ':', dribble[n]))

This program gives several examples of output formatting. One of the major tools in this area is the % operator. It is an operator which takes a string as its left argument, and a single value or a tuple as its right argument. It then examines the string (left argument) for % constructs of the sort which C printf uses, matches them in order with data items from the right, and forms a new string string substituting the data values for the % constructs.

Since the % returns the resulting string, it is most like sprintf in C. This string may then be printed with the usual Python print statement. There is one very important difference from C: The Python % operator is able to check that number and types of the data items match the number types of the % constructs, and throws an exception if these do not match. That's generally more polite than C, which cannot check, and will generally core dump or do something bizarre if these do not agree.
<<Sorting Reading Files>>