F-String Formatting And Alignment

Render numbers, dates, and tables with f-string format specs — alignment, padding, and precision without printf-style confusion.

PythonData Integrity

Code

pythonsnippet
24 lines
from datetime import date


def main() -> None:
    price = 1234.5678
    qty = 7

    # 精度与千分位
    print(f'{price:,.2f}')

    # 对齐与填充:左对齐文本、右对齐数字
    print(f'{"item":<10}{"qty":>5}{"price":>12}')
    print(f'{"widget":<10}{qty:>5}{price:>12,.2f}')

    # 日期与表达式内嵌
    print(f'as of {date.today():%Y-%m-%d}: {qty * price:,.0f}')

    # 调试语法(3.8+):变量名自打印
    ratio = qty / 10
    print(f'{ratio=:.2f}')


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1,234.57
item        qty       price
widget        7    1,234.57
as of 2026-11-16: 8,642
ratio=0.70

How it works

F-String Formatting And Alignment reduces to the function main.

Putting it to use

Expect labeled output — as of — when the file runs.

Output is labeled for readability — expect lines prefixed with as of.

Interactive Tools for This Topic

FAQ

What does F-String Formatting And Alignment print when run?
Running the file directly is enough — expect labeled output lines such as `as of`.