Python字符串的格式化输出


简单记录两种方法,第一种和Java、C++语言中一样,使用占位符;第二种format()方法。

  1. 使用占位符(%d, %f, %s, %x)
In [1]: 'Hello,%s' % 'world'
Out[1]: 'Hello,world'

In [2]: 'Hi,%s,you have $%d' % ('Michael', 100000)
Out[2]: 'Hi,Michael,you have $100000'
  1. 使用format(),用传入的参数依次替换字符串内的占位符{0}、{1}
In [2]: 'Hi,%s,you have $%d' % ('Michael', 100000)
Out[2]: 'Hi,Michael,you have $100000'

In [8]: '{1} {0} {1}'.format('hello', 'world')
Out[8]: 'world hello world'

In [9]: '{2} {0} {1}'.format('hello', 'world', 'tzz')
Out[9]: 'tzz hello world'