Output Formatting

For the haters in the audience - I'll get into the .format() method sometime in the future. I come from a school of thought that you need to evolve in your understanding as languages evolved - start procedural then get into object orientation and so forth.


This is the "old" way but it's easy to understand and learn - it has its roots in the C programming language's printf function. The term output formatting refers to making data look a certain way during output. For example, if the value of a variable pi is 3.1415926, but you didn't want that much space taken up on the screen, output formatting is your friend.

Try the following:

pi=3.1415926 # sets the value of the variable pi

print(pi) # prints 3.1415926 ... duh

print("%f" % pi) # creates a template string - the %f is the

# placeholder for a float

# then inserts the value of the variable pi

# interestingly outputs: 3.141593 (rounding?)

print("PI: %f" % pi) # shows how you can use

# placeholders anywhere in a string.

output="PI: %f" # assign the template string to a variable

print(output % pi) # shows the same output as above

# you can use a template in a string variable

print("PI: %.2f" % pi) # the %.2f says we want 2 places

# after the decimal: PI: 3.14 is output.

Look at the following interesting examples:

print("PI: %6.2f" % pi) # outputs - PI: 3.14

# notice the spaces before 3.14

# it's a 6 character field width

print("PI: %06.2f" % pi) # this time - PI: 003.14

# same 6 character field width

# but this time filled in with 0's

If you have more than one value to fill in, it needs to be in a tuple (comma separated list in parentheses)

print("Age: %i Height: %i'%i\"" % (16,5,10))

The general format is: %[flags][width][.precision]type

You can use templating or output formatting for the following types:

Next Post: Put Two Things on the Same Line

Recent Posts