lang/python/ FStrings


x = 257
y = 1.554
f"{x} {x:05d} {x:08x} {x:o}"
f"{y:e} {y:.2f} {0.5:.2%}"
z = 24242224224
f"{z:,.2f}"
# Alignment
f"{1:<8d} {1:<8d} {1:<8d}"
#vs
f"{1:>8d} {1:>8d} {1:>8d}"

Padding

You can specify left, centre or right alignment using <, > or ^, and the padding symbol before this. You can use a variable as the padding symbol provided it is a single-character string.

>>> a = 1
>>> b = 3.14
>>> c = "hello"
>>> width = 30
>>> f"{c:#^{width}}"
'############hello#############'
>>> f"{c:_<{width}}"
'hello_________________________'
>>> f"{c:*>{width}}"
'*************************hello'
>>> d="_*_"
>>> f"{c:{d}>{width}}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier
>>> d="*"
>>> f"{c:{d}>{width}}"
'*************************hello'