字符串格式化输入

BASIC

通过通过和关键字参数调用

1
2
3
4
5
6
7
8
9
template = '{0}, {1} and {2}'
template.format('a', 'b', 'c') ## by position
template = '{motto}, {pork} and {food}'
template.format(motto = 'spam', pork = 'ham', food = 'eggs') ## by keywork
template = '{motto}, {0} and {food}'
template.format('ham', motto = 'spam', food = 'eggs') ## by both

添加键、属性和偏移量

键值和属性

1
2
3
import sys
'My {1[spam]} runs {0.platform}'.format(sys, {'spam':'laptop'})



偏移量 (正的偏移量才能在格式化字符串的语法中有效)

1
2
somelist = list('SPAM')
'first={0[0]}, third={0[2]}'.format(somelist)

添加具体格式化

{fieldname!conversionflag:formatspec}

  • fieldname:指定参数的一个数字或关键字
  • conversionflag:可以是r、s,或者分别是改值上对repr、str或ascii内置函数的一次调用
  • formatspec:指定如何表示改值,包括字段宽度、对齐方式、补零、小数点精度等,形式如:[[fill]align[sign][#][0][width][.precision][typecode]]