Python
Published

February 26, 2024

Python f-strings

Here are some examples of f-strings in Python inspired by a post and a cheat sheet.

a = 2
b = 3
f"{a} + {b}"
'2 + 3'
f"{a=} and {b=}"
'a=2 and b=3'
f"a + b = {a+b}"
'a + b = 5'

Curly brackets in an f-string

n = 123

f'{{}}-{n}-{{{n}}}'
'{}-123-{123}'

Number formatting

var = 1234567890.1234

f'{var:,}'
'1,234,567,890.1234'
f'round: {var:.2f}'
'round: 1234567890.12'
f'comma: {var:,}'
'comma: 1,234,567,890.1234'
f'comma: {var:,.2f}'
'comma: 1,234,567,890.12'
import datetime

dt = datetime.datetime(2026, 2, 21, 19, 45, 30)

f'{dt}'
'2026-02-21 19:45:30'
f'{dt:%Y-%m-%d}'
'2026-02-21'
f'{dt.isoformat()}'
'2026-02-21T19:45:30'