F-String Formatting And Alignment
Render numbers, dates, and tables with f-string format specs — alignment, padding, and precision without printf-style confusion.
Code
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.70How 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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.