Python f-String Formatting Codes

Here is my short list about the common f-string formatting codes in Python:

>>> score = 123.728
>>> f"{score}"
'123.728'

Minimum field length:
>>> f"{score:>10}"
'   123.728'
>>> f"{score:<10}"
'123.728   '
>>> f"{score:^10}"
' 123.728  '

Number of decimals:
>>> f"{score:.2f}"
'123.73'
>>> f"{score:10.2f}"
'    123.73'
>>> f"{score:<10.2f}"
'123.73    '

Padded with a character:
>>> f"{score:0>10.2f}"
'0000123.73'
>>> f"{score:x>10.2f}"
'xxxx123.73'

Signed:
>>> f"{score:+.2f}"
'+123.73'

See also:

Updated: November 5, 2022 — 20:51

Leave a Reply