Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

The string.Formatter supports the same language that the str.format method supports. Practically, it parses expressions contained with {} according to what Python calls format string syntax. Everything outside of {} is preserved as is, while anything within {} is parsed for the field_name!conversion:format_spec specification. So, as our field_name doesn't contain ! or :, it can be anything else.

The field_name extracted is then provided to Formatter.get_field to look up the value of that field in the provided arguments of the format method.

So, for example, take an expression like:

string.Formatter().format("Hello {name}", name='Alessandro')

This leads to:

Hello Alessandro

Because the {name} is identified as a block to parse, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content