template = '{0}, {1} and {2}'
template.format('spam', 'ham', 'eggs')
# spam, ham and eggs
template = '{motto}, {pork} and {food}'
template.format(motto = 'spam', pork = 'ham', food = 'eggs')
# spam, ham and eggs
template = '{motto}, {0} and {food}'
template.format('ham', motto = 'ham', food = 'eggs')
'{motto}, {0} and {food}'.format(42, motto=3.14, food = [1,2])
# '3.14, 42 and [1,2]'
>>> import sys
>>> '{1[spam]} and {0.platform}'.format(sys, {'spam':'laptop'})
out: laptop and win32
>>> '{config[spam]} and {sys.platform}'.format(sys = sys, config = {'spam':'laptop'})
out: laptop and win32
>>> somelist = list('SPAM') # ['S', 'P', 'A', 'M']
>>> 'first = 0[0] and second = 0[1]'.format(somelist)
out: first = S and second = P
str.format()的替代目标语法
形式化结构:{fieldname!conversionflag:formatspec}
- fielname 是指定参数的一个数字或关键字,后面跟着可选的“.name”或“[index]”成分引用
- conversionflag 可以是r, s, 或者a分别是在该值上对rper, str 或ascii内置函数的一次调用
formatspec 指定了如何表示该值,包括字段宽度,对齐方式,补零,小数点精度等细节,并且以一个可选的数据类型编码结束。
formatspec 组成形式如下:
[[fill]align][sign][#][0][width][.precision][typecode]
- align 可能是>, <,= 或 ^ , 分别表示左对齐,右对齐,一个标记字符后的补充或居中对齐
- formatspec 也包含嵌套的,只带有{}的格式化字符串,它从参数列表动态地获取值
>>> '{0:10} = {1:10}'.format('spam', 123.456) # 第一个位置参数,10个字符宽
out: 'spam = 123.456'
>>> '{0:>10} = {1:<10}'.format('spam', 123.456) # 第一个位置参数右对齐,10个字符宽;第二个位置参数左对齐,10个字符宽
out:' spam = 123.456 '
>>> '{0.platform:>10} = {1[item]:<10}'.format(sys, dict(item='laptop'))
out:' win32 = laptop '
>>> '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)
out: 3.141590e+00, 3.142e+00, 3.14159
>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)
out: 3.141590, 3.14, 003.14
# {2:g} 表示第三个参数默认根据“g”浮点数表示格式化
# {1:.2f}指定了带有2个小数位的“f”浮点数格式
# {2:06.2f}添加一个6字符宽的字段并且在左边补充0
>>> '{0:.{1}f}'.format(1/3.0, 4)
out: 0.3333
原文:https://www.cnblogs.com/xiaofeiIDO/p/12050089.html