String Formatting

Often it is desirable to precisely control the output of strings.

This output control can mean, for example, alignment in columns or the specification of the number of digits to the right of a decimal point.

Python provides a flexible string formatting approach.

Operators and Types

We have seen that the following are two entirely different things:

value1 = 27 + 8 # Integer addition
value2 = '27' + '8' # String concatenation
print(value1)
print(value2)

What is output by the code above?

The type of operands for the + determine the operation performed.

The % Operator

The % as an operator similarly has two meanings.

  1. The % is the mod/remainder if its operands are integers
  2. The % is the string formating operator if its left operand is a string and its right operand is a parenthisized list

Also for a third meaning % is used in format strings as placeholders for values that will be plugged in to the format string.

This is not a confusing as it seems.

rem = 27 % 5 # Mod/remainder
msg = 'Remainder: %d' % (rem) # String formatting
print(rem)
print(msg)

Uses in the above example:

  1. Remainder operator
  2. Format string placeholder
  3. Format operator

% and String Formatting

When formatting strings with % the left operand is the format string and the right operand is a list of items in parenthesis.

The format string contains placeholders that begin with %.

The list contains as many items as there are placeholders in the format string.

The result of a string formatting operations is a string that has the format string placeholders replaced by values from the list.

The first list value replaces the first placeholder, ...

% Placeholders

The basic placeholders:

  • %d - Integer (decimal) placeholder
  • %f - Float placeholder
  • %s - String placeholder

Immediately after the % can be some additional formatting specifiers.

Some useful examples:

  • %6d - Integer in a field width of 6.
  • %.2f - Float placeholder, two digits to the right of the decimal point
  • %-10s - String placeholder, field width of 10, left justified

Field width is useful for column alignment.

For more details see Python Documentation.

String Formatting Example

Example:

names = ['Joe', 'Jane']
ave = [18.977, 4.5 ]
size = [ 4, 7 ]
format = '%-8s\'s average is %5.2f and his size is %d'
line = format % (names[0], ave[0], size[0])
print(line)
line = format % (names[1], ave[1], size[1])
print(line)

Output:

Joe's average is 18.98 and his size is 4

Jane's average is 4.5 and his size is 7

Note in the code above that you can use a single quote within a double quote string and vice versa.