str.format

常用%来格式化字符串输出:

>>> first = 'Reuven'
>>> last = 'Lerner'
>>> "Good morning, %s %s" % (first, last)

'Good morning, Reuven Lerner'

使用str.format格式化字符串输出:

>>> first = 'Reuven'
>>> last = 'Lerner'
>>> "Good morning, {} {}".format(first, last)

'Good morning, Reuven Lerner'

以相反的顺序输入参数:

>>> first = 'Reuven'
>>> last = 'Lerner'
>>> "Good morning, {1} {0}".format(first, last)

'Good morning, Lerner Reuven'

参数为序列:

>>> names = ('Reuven', 'Lerner')
>>> "Good morning, {} {}".format(*names)

'Good morning, Reuven Lerner'

参数为字典:

>>> person = {'first':'Reuven', 'last':'Lerner'}
>>> "Good morning, {first} {last}".format(**person)

'Good morning, Reuven Lerner'

别这么用:

>>> person = {'first':'Reuven', 'last':'Lerner'}
>>> "Good {0}, {first} {last}".format('morning', **person)

'Good morning, Reuven Lerner'

fixed-width field:

>>> "Your name is {name:10}".format(name="Reuven")

'Your name is Reuven    '
  • < 左对齐
  • > 右对齐
  • ^ 居中
  • = 只对numeric类型 eg. +000000120
>>> "Your name is {name:*^10}".format(name="Reuven")

'Your name is **Reuven**'

可用的integer表现类型:

>>> "The price is ${number:x}.".format(number=123)

'The price is $7b.'

>>> "Your call is important to us. You are call #{number:05}.".format(number=123)

'Your call is important to us. You are call #00123.'
  • b 二进制
  • c 字符
  • d 十进制
  • o 八进制
  • x 十六进制(小写)
  • X 十六进制(大写)
  • n 数字,和d一样
  • Noned一样

总结:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"