Skip to content. | Skip to navigation

Personal tools
You are here: Home Knowledge PyCon 2010 Presentation: str.format()

PyCon 2010 Presentation: str.format()

I gave this talk at PyCon 2010. Here are the slides and some larger code examples that I couldn't include in the talk for space reasons.

My talk covered Advanced String Formatting for Python, commonly called "str.format()". This is a feature I implemented for Python 2.6+ and 3.0+. It's described in PEP 3101.

Here are the slides in the original Apple Keynote format. They're also available in an exported PowerPoint format. I can't promise that all of the fonts look correct in the PowerPoint version.

While preparing this talk I realized that there's an issue with Python 2.7 and 3.1 that breaks earlier uses for format() with complex numbers, if a format string is specified that is recognized by str but not by complex. I've open Python issue 7994 to track this problem, and I'll modify Python 2.7 and 3.2 to have a PendingDeprecationWarning that warns about this usage. In Python 3.4 it will be an error to specify a format string on a type that doesn't provide __format__.

In the talk I discussed a library I'm developing that aids in migrating from the older %-formatting to str.format(). If you look at the accompanying slides, the discussion starts on slide 34.

Here's the simplified source to my library. The full version (with tests and support routines) is available. This is an active project of mine, so I will be making periodic updates to the code.

def expand_str_mapping(fmt, kwargs):
    '''fmt is either a %-formatting format string, or a
       str.format() format string. We guess which one and call
       the appropriate routine.
       kwargs is a mapping (probably a dictionary) used to expand
       the format string.'''

    t = _is_definitely_percent_mapping(fmt)
    if t is True:
        # It's definitely a %-formatting format string
        return fmt % kwargs
    if t is False:
        # It's definitely a str.format() format string
        return fmt.format(**kwargs)

    # We'll need to guess. There are pathological cases like
    #  "{abc:%(abc)s}" that are valid for both, so in general
    #  it's impossible to get this exactly correct. But we can
    #  do pretty good.
    t = _is_probably_percent_mapping(fmt, kwargs)
    if t is True:
        return fmt % kwargs
    if t is False:
        return fmt.format(**kwargs)

    # We really have to guess. Guess str.format first.
        return fmt.format(**kwargs)
    except TypeError:
        return fmt % kwargs
Document Actions
« April 2017 »