liveBook · Manning

Format method

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

str.format() is a Python string method that produces a new string by replacing formatting fields with supplied values.

str.format() creates a new string from a template. Curly braces mark placeholders, and positional arguments fill them in the order the placeholders appear. section 2.1.12

Insert values into a phrase

article = 'an'\nword = 'octopus'\nphrase = 'Ahoy, Captain, {} {} off the larboard bow!'.format(article, word)\nprint(phrase)\n# Ahoy, Captain, an octopus off the larboard bow!

Use formatting fields to control displayed values:

  • Use a field width such as {:8} to align text or numbers into columns; text is left-justified and numbers right-justified. section 6.1.4

Choose str.format() or an f-string for many interpolation tasks. F-strings place variables or expressions directly inside the braces, while both forms support printf-style formatting options. section 2.3.4 section 6.5

Format generated output

A loop can select values, join adjective strings, and use str.format() to assemble repeated output such as insults with fixed punctuation and wording. section 9.1.5

>>> 'Pi is {:0.02f}'.format(math.pi)
'Pi is 3.14'

Compare unformatted and precision-controlled output for math.pi. section 6.1.4

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains placeholders, positional arguments, precision, field width, and justification, but does not detail advanced formatting internals.
Examples
Demonstrates nautical phrases, formatted π values, aligned columns, word-count output, and generated insults.
What it assumes
Assumes basic Python variables and strings while teaching templates, substitution order, and formatting fields through examples.
What you can do after
Apply str.format() to build reusable output templates, set numeric precision, and align text or numbers into columns.
How it connects
Connects string formatting with string concatenation, f-strings, string joining, loops, and command-line output.

Also explained in

Compare how 3 books explain format method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.