Search

Using The Python String Format Method: Format Specifications Part 2

In an earlier post, I showed how to use field names and conversion fields to format values in replacement fields. Today, I will continue that discussion by showing how to use format specifications, the optional and last feature of replacement fields, in the python string format method.

The format specification for python string format method
 

The format specifications represent how the value in the replacement field should be presented. It includes details such as the width of the field, its alignment, padding, conversion etc. Each value type is given its own specification. Also note that each format specification can include nested replacement fields but the level of nesting should not be deep.

You use a colon, :, to denote the start of a format specification. The format specification has 8 flags and I will denote each of them in their order of precedence. Note that each of the flags are optional.

  1. The fill flag
  2. This flag is used as the first flag. Use it to denote what you want to use to fill the space in the presentation of the value of the object. Any character can be used as the fill character and if it is omitted, it defaults to a space. Note that a curly brace cannot be a fill character except the curly brace is in a nested replacement field. The fill character kicks in when the value of the object cannot fill the specified width of the replacement field otherwise it doesn’t apply. So, you use it with other flags.

  3. The align flag
  4. The represents the alignment of the value of the object. You could either right align, left align, center or cause a padding to fill the available space. The different options are presented below:

    < Used for left alignment of the value in the available space. The default for most objects
    > used for right alignment of the value in the available space. The default for numbers.
    = Forces a padding to be placed after the sign but before the digits. Only valid for numeric types. If you precede the field width (explained below) with 0, then this becomes the default.
    ^ forces the value to be centered within the available space.

    To make the alignment option meaningful, you must specify a minimum field width. Here are some examples. They all come with minimum field width of 20.

  5. The sign flag
  6. This is only used for numeric values. The various options are:

    + Use a sign for both positive and negative values.
    - Use a sign only for negative values (this is the default behavior)
    Space Show a leading space for positive numbers and a minus sign on negative numbers.

    Here are some examples.

  7. The alternate flag, #.
  8. Use this flag when you are doing value conversion and you want the alternate option to be specified. It is valid for integers, floats, decimal and complex types. We will come back to this when we get to the conversion flag and show how the alternate forms can be specified.

  9. The grouping flag.
  10. The grouping flag specifies the character to be used as a thousands separator. It has two options:

    _ Use this as a thousands separator for the integer types when ‘d’ is specified as the type flag (to be explained later) and floating point types. When the type flag for integer types is either ‘b’, ‘o’, ‘x’, or ‘X’, the separator is inserted after every four digits.
    , Use a comma as the thousands separator. You could use the ‘n’ type flag instead if you want a locale aware separator.

    Now some examples. I included the third example with ‘b’ as a type flag. ‘b’ as type flag means convert value to base 2. This will be explained below under type flags.

  11. The precision flag
  12. The precision flag is a decimal number that indicates how many digits should be displayed “after” the decimal point for a floating point value that has the type flag ‘f’ or ‘F’, or before and after the decimal point for a floating point value that has the type flag ‘g’ or ‘G’. Note that there is no precision for integer types. If the value is a non-numeric type, then this indicates the maximum field size of the replacement field.

    Now for some examples. Notice how it truncates the string type, s, when the precision is smaller than the number of characters.

  13. The type flag
  14. The type flag determines how the data should be presented. The type flag is specified for string types, integer types, and floating point types.

    For string types: The available options are...

    s The default type for strings and may be omitted
    None The same as ‘s’

    For integer presentation types: The options are...

    b Outputs the number in binary format
    c Converts the value to the corresponding Unicode character before printing.
    d Output the number in base 10 before printing.
    o Octal format. Output the number in base 8 and print.
    x Hex format. Output the number in base 16 using lower case letters for digits above 9
    X Hex format. Output the number in base 16 using Upper case letters for digit above 9.
    n Decimal format. The same as ‘d’ but it uses locale aware setting to insert appropriate thousands separator for the locale.
    None Same as ‘d’

    Note that except for ‘n’ and None, you can use any of the options above in addition to the floating point types below for integers. That is, you can have a mixture of both integers and floating points.

    Now, let’s use some examples.

    When discussing the alternate flag, #, I stated that there are times when you want alternate conversion forms to be specified. For example, for binary, octal and hexadecimal outputs the alternate flag, #, will result in an output of ‘0b’, ‘0o’, and ‘0x’. Let’s show this with examples.

    The alternate flag can also be applied to floats and complex numbers.

    Now finally, the options for floating point presentation types are:

    e Exponent notation. Print the number in scientific notation using the exponent, e, to denote it. The default precision is 6.
    E Exponent notation. Print the number in scientific notation using the exponent, E, to denote it.
    f Displays the number in fixed point notation. The default precision is 6.
    F Fixed point notation, just like ‘f’ but converts nan to NAN and inf to INF.
    g This is the general format. Uses fixed point or scientific format depending on the magnitude of the number.
    G General format, but in uppercase.
    n Same as ‘g’ but is locale aware in inserting appropriate thousands separator.
    % Percentage. Multiplies the number by 100 and displays it in fixed format, ‘f’, with a percent sign (%) following it.
    None Similar to ‘g’ except that fixed point notation when used has at least one digit past the decimal point.

    The following examples uses precision 2 then the default 6.

I hope you get creative in using this format specifications. They are very helpful when representing values. Note that python’s literal string formatting method, f-strings, are similar to the python string format method described here. You can interchange the two.

No comments:

Post a Comment

Your comments here!

Matched content