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).

Created by

Trainings, coaching and development for pytest, Qt and other Python/development topics.

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, .

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:

In [1]:

```
one = 1
two = 2
```

In [2]:

```
f"{one}, {two}"
```

Out[2]:

'1, 2'

You can put any Python code into f-strings:

In [3]:

```
f"{one} + {two} = {one + two}"
```

Out[3]:

'1 + 2 = 3'

This can also be used to access dictionary entries:

In [4]:

```
colors = {
"red": "#ff0000",
"green": "#00ff00",
"blue": "#0000ff",
}
```

In [5]:

```
f"red: {colors['red']}"
```

Out[5]:

'red: #ff0000'

Similarly, you can access list items:

In [6]:

```
data = [4, 8, 15, 16, 23, 42]
```

In [7]:

```
f"Best numbers: {data[4]} and {data[5]}"
```

Out[7]:

'Best numbers: 23 and 42'

Or attributes:

In [8]:

```
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
pos = Point(23, 42)
```

In [9]:

```
f"{pos.x}, {pos.y}"
```

Out[9]:

'23, 42'

Or even call functions:

In [10]:

```
f"bigger value: {max(pos.x, pos.y)}"
```

Out[10]:

'bigger value: 42'

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

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

In [11]:

```
from datetime import date
user = "eric_idle"
member_since = date(1975, 7, 31)
delta = date(2022, 4, 11) - member_since
```

In [12]:

```
f"{user=} {member_since=}"
```

Out[12]:

"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

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

In [13]:

```
f"{user=!s} {delta.days=:,d}"
```

Out[13]:

'user=eric_idle delta.days=17,056'

Whitespace around the `=`

is preserved in the output:

In [14]:

```
f"{user = }"
```

Out[14]:

"user = 'eric_idle'"

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

In [15]:

```
from math import cos, radians
theta = 30
```

In [16]:

```
f"{theta=} {cos(radians(theta))=:.3f}"
```

Out[16]:

'theta=30 cos(radians(theta))=0.866'

Since f-strings support running any code, just call `repr(...)`

on your object:

In [17]:

```
class Data:
def __repr__(self):
return '<Data ...>'
def __str__(self):
return 'string representation'
data = Data()
```

In [18]:

```
f"data: {data}"
```

Out[18]:

'data: string representation'

In [19]:

```
f"data: {repr(data)}"
```

Out[19]:

'data: <Data ...>'

Alternatively, use the `!r`

suffix like with `.format()`

:

In [20]:

```
f"data: {data!r}"
```

Out[20]:

'data: <Data ...>'

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):

In [21]:

```
f"data: {data!s}"
```

Out[21]:

'data: string representation'

In [22]:

```
val = "test"
```

In [23]:

```
f"{val:>10}"
```

Out[23]:

' test'

Align left:

In [24]:

```
f"{val:<10}"
```

Out[24]:

'test '

You are able to choose the padding character:

In [25]:

```
f"{val:_<10}"
```

Out[25]:

'test______'

And also center align values:

In [26]:

```
f"{val:^10}"
```

Out[26]:

' test '

By default, strings are left-aligned:

In [27]:

```
f"{val:10}"
```

Out[27]:

'test '

but numbers are right-aligned:

In [28]:

```
answer = 42
```

In [29]:

```
f"{answer:10}"
```

Out[29]:

' 42'

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:

In [30]:

```
archive = 'zip'
```

In [31]:

```
f"{archive:^6}"
```

Out[31]:

' zip '

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.

In [32]:

```
instrument = "xylophone"
```

In [33]:

```
f"{instrument:.5}"
```

Out[33]:

'xylop'

It is also possible to combine truncating and padding:

In [34]:

```
f"{instrument:10.5}"
```

Out[34]:

'xylop '

Integers:

In [35]:

```
answer = 42
```

In [36]:

```
f"{answer:d}"
```

Out[36]:

'42'

Floats:

In [37]:

```
import math
```

In [38]:

```
f"{math.pi:f}"
```

Out[38]:

'3.141593'

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

In [39]:

```
f"{answer:o}"
```

Out[39]:

'52'

hexadecimal (lower- or uppercase):

In [40]:

```
f"{answer:x}, {answer:X}"
```

Out[40]:

'2a, 2A'

or binary:

In [41]:

```
f"{answer:b}"
```

Out[41]:

'101010'

A `#`

can be used to add a suitable prefix (`0o`

, `0x`

and `0b`

, respectively):

In [42]:

```
f"{answer:#x}"
```

Out[42]:

'0x2a'

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

In [43]:

```
f"{answer:c}"
```

Out[43]:

'*'

displaying it in scientific notation (`E`

instead of `e`

for uppercase):

In [44]:

```
f"{answer ** 8:e}"
```

Out[44]:

'9.682652e+12'

or selecting scientific notation automatically for larger numbers (`G`

instead of `g`

for uppercase):

In [45]:

```
f"{answer:g}, {answer ** 8:g}"
```

Out[45]:

'42, 9.68265e+12'

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

In [46]:

```
f"{answer:4d}"
```

Out[46]:

' 42'

Like for strings, the padding character can be selected:

In [47]:

```
f"{answer:04d}"
```

Out[47]:

'0042'

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.

In [48]:

```
f"{math.pi:06.2f}"
```

Out[48]:

'003.14'

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

In [50]:

```
f"{answer:06.2d}"
```

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

In [51]:

```
f"{answer:+d}"
```

Out[51]:

'+42'

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.

In [52]:

```
f"{answer: d}"
```

Out[52]:

' 42'

In [53]:

```
f"{-answer: d}"
```

Out[53]:

'-42'

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

In [54]:

```
f"{-answer:=5d}"
```

Out[54]:

'- 42'

In [55]:

```
f"{answer:=+5d}"
```

Out[55]:

'+ 42'

It's possible to use either `,`

or `_`

as a thousands separator when displaying large numbers:

In [56]:

```
num = 1234567890
```

In [57]:

```
f"{num:d}"
```

Out[57]:

'1234567890'

In [58]:

```
f"{num:,d}"
```

Out[58]:

'1,234,567,890'

In [59]:

```
f"{num:_d}"
```

Out[59]:

'1_234_567_890'

Like `.format()`

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

In [60]:

```
from datetime import datetime
dt = datetime(2022, 4, 11, 13, 37)
```

In [61]:

```
f"{dt:%Y-%m-%d %H:%M}"
```

Out[61]:

'2022-04-11 13:37'

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:

In [62]:

```
value = "test"
align = "^"
width = 10
```

In [63]:

```
f'{value:{align}{width}}'
```

Out[63]:

' test '

Parametrized precision:

In [64]:

```
value = "pizza"
prec = 2
```

In [65]:

```
f"{value:.{prec}} = {math.pi:.{prec}f}"
```

Out[65]:

'pi = 3.14'

Width and precision:

In [66]:

```
width = 5
```

In [67]:

```
f"{math.pi:{width}.{prec}f}"
```

Out[67]:

' 3.14'

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

In [68]:

```
dfmt = "%Y-%m-%d"
tfmt = "%H:%M"
```

In [69]:

```
f"{dt:{dfmt} {tfmt}}"
```

Out[69]:

'2022-04-11 13:37'

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.

In [70]:

```
class HAL9000:
def __format__(self, fmt):
if fmt == "open-the-pod-bay-doors":
return "I'm afraid I can't do that."
return "HAL 9000"
hal9000 = HAL9000()
```

In [71]:

```
f"{hal9000:open-the-pod-bay-doors}"
```

Out[71]:

"I'm afraid I can't do that."

To use `{`

or `}`

inside an f-string, double them:

In [72]:

```
f"Literal braces: {{value}}"
```

Out[72]:

'Literal braces: {value}'

Starting with Python 3.12, nested quotes (as well as backslashes) are freely allowed inside of `{...}`

in an f-string (PEP 701 – Syntactic formalization of f-strings).

For Python versions before 3.12, 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:

In [73]:

```
f"I'm an fstring"
f'"Use fstrings", he said!'
```

Out[73]:

'"Use fstrings", he said!'

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

In [74]:

```
f"The string above contains: \"I'm an fstring\""
```

Out[74]:

'The string above contains: "I\'m an fstring"'

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:

In [75]:

```
f"red: {colors['red']}"
```

Out[75]:

'red: #ff0000'

Using the same quotes would end the string:

In [76]:

```
f"red: {colors["red"]}" # WRONG
```

Input In [76] f"red: {colors["red"]}" # WRONG ^ SyntaxError: f-string: unmatched '['

And backslashes won't work either:

In [77]:

```
f"red: {colors[\"red\"]}" # WRONG
```

But triple-quotes work great:

In [ ]:

```
f"""red: {colors["red"]}"""
```

Or you can use a temporary variable instead.