Skip to content

Latest commit

 

History

History
28 lines (22 loc) · 712 Bytes

20240228143839.md

File metadata and controls

28 lines (22 loc) · 712 Bytes

f-string formatting techniques

Basic f-strings are already awesome, but there's a lot you can do after the : including:

• align data left or right • set column widths • use decimal places

A quick example below ...

stocks = [
    {"symbol": "AAPL", "name": "Apple Inc.", "price": 150.10},
    {"symbol": "MSFT", "name": "Microsoft Corp.", "price": 295.36},
    {"symbol": "GOOG", "name": "Alphabet Inc.", "price": 2732.16},
]
for stock in stocks:
    print(f"{stock['symbol']:<6} {stock['name']:<20} {stock['price']:>10.2f}")

# Nicely formatted output:
"""
AAPL   Apple Inc.               150.10
MSFT   Microsoft Corp.          295.36
GOOG   Alphabet Inc.           2732.16
"""

#f-strings