Python f-strings¶

All currently supported Python versions (3.6+) support string-formatting via f-strings. While PEP 498 (Literal String Interpolation) as well as the Python documention (tutorial, syntax reference) have some information on their usage, I was missing a reference which is terse, but still verbose enough to explain the syntax.

Thus, fstring.help was born, made with and
(initially as a quick hack at PyConDE 2022).

Some content is copied verbatim from pyformat.info (Copyright 2015 Ulrich Petri, Horst Gutmann). Thanks!

Cheat sheet tables can be found at fstring.help/cheat thanks to Trey Hunner.

Repository on Github, contributions welcome! If you prefer an interactive version, .

Basic formatting¶

f-strings are strings with an f in front of them: f"..." or f'...'. Inside the f-string, curly braces can be used to format values into it:

Arbitrary code¶

You can put any Python code into f-strings:

This can also be used to access dictionary entries:

Similarly, you can access list items:

Or attributes:

Or even call functions:

Note, however, that this should be used with care: Complex expressions are better first assigned to a variable.

Using f-strings for debugging¶

Debug expressions¶

Python 3.8 added support for self-documenting expressions and debugging - some examples adapted from the "what's new" document:

The usual f-string format specifiers (see below) allow more control over how the result of the expression is displayed:

Whitespace around the = is preserved in the output:

The whole expression is displayed, so that calculations can be shown:

Printing debug representation (repr)¶

Since f-strings support running any code, just call repr(...) on your object:

Alternatively, use the !r suffix like with .format():

An !s suffix to convert to a string explicitly is also supported, though often not needed (as this is the default behavior in most cases):

By default, values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length.

Align right:

Align left:

You are able to choose the padding character:

And also center align values:

By default, strings are left-aligned:

but numbers are right-aligned:

When using center alignment, where the length of the string leads to an uneven split of the padding characters, the extra character will be placed on the right side:

Truncating long strings¶

Inverse to padding, it is also possible to truncate overly long values to a specific number of characters.

The number behind a . in the format specifies the precision of the output. For strings, that means that the output is truncated to the specified length. In our example, this would be 5 characters.

It is also possible to combine truncating and padding:

Numbers¶

Integers:

Floats:

Other number representations¶

Numbers can also be represented in other bases, such as octal:

or binary:

A # can be used to add a suitable prefix (0o, 0x and 0b, respectively):

Some other representations are available too, such as converting the number into an unicode character:

displaying it in scientific notation (E instead of e for uppercase):

or selecting scientific notation automatically for larger numbers (G instead of g for uppercase):

Similar to strings, numbers can also be constrained to a specific width.

Like for strings, the padding character can be selected:

Again similar to truncating strings, the precision for floating point numbers limits the number of positions after the decimal point.

For floating points, the padding value represents the length of the complete output. In the example below, we want our output to have at least 6 characters, with 2 after the decimal point.

For integer values, providing a precision doesn't make much sense and results in a ValueError:

Signed numbers¶

By default, only negative numbers are prefixed with a sign. This can be changed of course.

Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used for positive ones.

It's also possible to control the position of the sign symbol relative to the padding.

Thousands separator¶

It's possible to use either , or _ as a thousands separator when displaying large numbers:

Datetime¶

Like .format(), f-strings also allow objects to control their own rendering. This for example allows datetime objects to be formatted inline:

Parametrized formats¶

Additionally, f-strings allow all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon.

Parametrized alignment and width:

Parametrized precision:

Width and precision:

The components of a date-time can be set separately:

Custom objects¶

The datetime example works through the use of the __format__() magic method. You can define custom format handling in your own objects by overriding this method. This gives you complete control over the format syntax used.

Escaping braces¶

To use { or } inside an f-string, double them:

Quotes usage¶

If you need to use single quotes inside an f-string, the easiest way is to use double-quotes for the string (and vice-versa), like with ordinary strings:

If you need to use single and double-quotes in the string, escape one of them - again, like with regular strings:

Things get a bit more troublesome when mixing quotes inside replacements: There, backslashes are not allowed. Usually, you can just use the other kind of string quotes, like we did in an earlier example:

Using the same quotes would end the string:

And backslashes won't work either:

But triple-quotes work great:

Or you can use a temporary variable instead.

Switching to f-strings¶

If you're still using "...".format(...) or the even older percentage-formatting ("..." % ...), tools like pyupgrade or flynt can help switching to f-strings.