String .format() method

Basic usage

Pythonic string formatting uses curly brackets {} as placeholders to add and format data within strings.

The two pairs of curly brackets {} in the string get replaced with the values of the two arguments question and answer of the string method .format(). Notice the dot . that connects the string with its method.

The .format() combines most advantages of the mix of alternative options:

  • Implicit type conversion: Any non-string data will be automatically converted to a string.

  • Good readabiltiy: The text with placehoders is separated from the data to be filled in.

  • Additional formatting options: E.g. how many decimals of a float shall be displayed.

  • Well supported: It works with all versions of Python since 2008 (= 2.6 and later)

Sequence options

Defaults

If the curly braces {} are left empty, the number of placeholders has to match the number of arguments and their sqeuences are identical.

Indices

Indices can be used to alter the sequence or insert argument values multiple times. Tuples and lists can also be used as argument if they are unpacked with a single asterisk *list.

Keywords

Keyword arguments can be used to alter the sequence or insert argument values multiple times. Dictionaries can also be used as argument if they are unpacked with a double asterisk **dict.

Formatting options

Defaults

Padding & alignment

Floats

Formatting options for float

Alternative options

String concatenation

Strings can also be added (= concatenated) together with the '+' operator.

Since only strings can be added to strings but not e.g. integers, explicit type conversion with the built-in str() function will be necessary for any non-string values.

Python 2 style %

Python 2 originally used a different syntax.

Before the .format() method was added to Python versions 2.6 and 3.0 in 2008, different placeholders (e.g. %s for string values and %d for decimal integers) and % instead of .format() had to be used.

Template strings

In 2004 the Template() class was added to the string module from the standard library to satisfy the Python enhancement proposal (PEP) 292.
NOTE: Since the in-browser version of Python used here supports only a subset of the standard library which does not include the Template() class, clicking ‘Run’ will throw an error.

Python 3.6 f-string

Python 3.6+ f-String formatting.

In 2016 formatted string literals (also called f-strings) have been added as another option, but they are not supported by any Python version prior to 3.6. Notice the f that precedes the string literal.

References

https://docs.python.org/3/library/string.html#formatstrings https://realpython.com/python-string-formatting/

Examples

https://pyformat.info