DAGDA SEARCH | Back to results | Support

Py3k String Formatting - Python Wiki

Source: https://wiki.python.org/python/py3/Py3kStringFormatting.html

  1. Python Wiki /
  2. Python Wiki /
  3. Python 3 Migration /
  4. Py3k String Formatting
View as Markdown

Py3k String Formatting

Legacy Wiki Page

This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org.

String formatting methods in Python 3000, based on PEP 3101

Author:

Andrea Bucciotti

Current formatting methods

Python 3.0 currently provides two methods of string interpolation:

  • The ‘%’ operator for strings.

  • The string.Template module.

The first one has been removed because, as a binary operator, it can take at most 2 arguments of which one is already dedicated to the format string. This makes ‘%’ operator quite unflexible and constraining.

On the other hand the string.Template module is felt that serves a distinct need and for that reason is not going to be removed or changed.

Get started: the new method, format!

The built-in string class (and also the Unicode class in 2.6) will gain a new method, ‘format’, which takes an arbitrary number of positional and keyword arguments.

This method can also be “customized”, but we’ll treat about this later.

Each argument can be identified with a positional number starting from 0, or with a keyword name:

"My name is {0}, and this is a {whatsthis} about string formatting in {2}".format('Andrea',whatsthis = 'tutorial','Python')

Which gives:

"My name is Andrea, and this is a tutorial about string formatting in Python"

instead of the old:

"My name is s%, and this is a s% about string formatting in s%" % ('Andrea','tutorial','Python')

Brace characters (‘curly braces’) are used to indicate a replacement field within the string:

"Hello, {0}.".format('world')

Braces can be escaped by doubling:

"Curly {0}: {{}}".format('braces')

The new string is:

"Curly braces: {}"

The element within the braces is called a ‘field’. Fields consist of a ‘field name’, which can either be simple or compound, and an optional ‘format specifier’.

Simple and Compound field names

A simple field name is a valid base-10 integer, or a valid Python identifier.

A compound field name is a combination of multiple simple field names in an expression. For example, a field whose field width is itself a parameter could be specified via:

"{0:{1}}".format(a, b)

By design you cannot embed arbitrary expressions in format strings.

Only two operators are supported: the ‘.’ (getattr) operator, and the ‘[]’ (getitem) operator.

This example shows the use of the ‘getattr’ or ‘dot’ operator in a field expression.

The dot operator allows an attribute of an input value to be specified as the field value. ..

“My name is {0.name}”.format(open(‘out.txt’, ‘w’))

This code creates a new empty file ‘out.txt’ in the current directory and returns the string:

"My name is out.txt"

Where ‘out.txt’ is the complete path to the file.

An example of the ‘getitem’ syntax:

"My name is {0[name]}".format(dict(name='Fred'))

It should be noted that the use of ‘getitem’ within a format string is much more limited than its conventional usage.

In the above example, the string ‘name’ really is the literal string ‘name’, not a variable named ‘name’.

Because keys are not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings “10” or “:-]”) from within a format string.

Format Specification

If an object does not define its own format specifiers, a standard set of format specifiers is used.

Explicit Conversion Flag

The explicit conversion flag is used to transform the format field value before it is formatted. Currently, two explicit conversion flags are recognized:

These flags are placed before the format specifier:

>>> "{0!r:20}".format("Hello")  # Double quotes
>>> "'Hello'             "

>>> "{0!s:20}".format("Hello")  # Single quote
>>> 'Hello               '

Customize the format method

The new, global built-in function ‘format’ simply calls this special method:

def format(value, format_spec):
    return value.__format__(format_spec)

Any class can override the __format__ method to provide custom formatting for that type:

class AST:
    def __format__(self, format_spec):
        ...

A final Example

Now, how do we stitch all this stuff toghether?

I’ll try to give you an example script that sum quite everything we saw:

# the following script generates random numbers and, using compound
# fields left aligns odd numbers and right aligns even numbers

import random

while True:
    a = random.randint(1, 10000000000)
    b = '<'
    if a % 2 == 0: # if it's even
        b = '>'

    print('{0: {1}20g}'.format(a,b))
PreviousPy3k Str Uni Tests Next Py3k to Do