str.format()高级用法与格式化规范mini-language
请深入讲解str.format()的语法规范(Format Specification Mini-Language),包括对齐方式、填充字符、数字格式化(千位分隔、百分号、进制)、datetime格式化,以及format_map()的用途。
回答
我还是少年
str.format()的完整语法:{field_name:format_spec}
Format Specification Mini-Language:
[[fill]align][sign][#][0][width][grouping_option][.precision][type]
1. 对齐与填充:
'<'左对齐,'>'右对齐,'^'居中,'='填充在符号后- 例:
'{:*^10}'.format('Hi')->'****Hi****'
2. 数字格式化:
'{:,.2f}'.format(1234567.89) # '1,234,567.89'(千位分隔)
'{:.2%}'.format(0.125) # '12.50%'(百分号)
'{:#x}'.format(255) # '0xff'(十六进制带前缀)
'{:b}'.format(10) # '1010'(二进制)
'{:+d} {: d}'.format(1, -1) # '+1 -1'(强制符号)
3. datetime格式化(datetime对象需自定义):
from datetime import datetime
'{:%Y-%m-%d %H:%M:%S}'.format(datetime.now())
4. format_map():
info = {'name': 'Alice', 'age': 30}
print('{name} is {age}'.format_map(info))
# 比format(**dict)安全,不会抛出KeyError之外的异常
# 支持自定义dict子类实现__missing__方法
5. 属性访问和索引:
'{0.x},{0.y},{1[0]}'.format(point, [1, 2, 3])
**注意:**自Python 3.6起,f-string性能更优,多数场景应优先使用f-string。