Marquette University, view of Wisconsin Avenue  

Module 15

String Formatting

Python has several ways of formatting strings. We will look first at the format method, as it has the most expressibility. For the format function, we distinguish between the blueprint - a string that describes how the formatted string looks - and the content - the variables that need to be put into the output. The blueprint uses curly brackets { } to denote where a variable can be stored. The format method has a variable number of arguments. If the blueprint's pairs of curly brackets does not contain indices, then the format method replaces each pair of curly brackets successively with the arguments. Otherwise, if the pair of curly brackets contain indices, then they will specify the argument to be put into a curly bracket.

After a colon, a curly bracket inside the blueprint contains a number of optional formatting instructions. A single integer specifies the width of the field. If the variable is longer, the field width is made appropriately larger, otherwise additional white spaces are added. The default alignment is to the left for strings and to the right for numerical values. We can use the caret ^ to specify centering, < for left alignment, and > for right alignment. We can specify the type of the variable using a single letter, s for string, d for a number (integer) in decimal form, f for a floating point number, and e for a floating point number with exponential notation. We can define the precision (number of digits after the decimal point) for floating point numbers using a digital point and the precision. For example, " {:8.2f }".format(3.14124) allocates a total of 8 spaces to the number, but has a precision of only two.

Since the blueprint uses curly brackets as meta-character, we need to have an escape sequence. This is done by just doubling the curly bracket.

Format strings are useful in controlling the output exactly, such as in writing tables. It can also be used to generate output that is ported into a markup language such as LaTeX.