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'

Datetime:
>>> import datetime
>>> d = datetime.datetime(2024,1,2,3,4,5)
>>> f"{d:Timestamp is %Y-%m-%d %H:%M:%S}"
'Timestamp is 2024-01-02 03:04:05'

See also:

Updated: February 7, 2024 — 15:46

Leave a Reply