PYTHON使用FORMAT函数格式化字符串

Python 3 中使用'{} {}'.format('one','two')函数替代'%s %s' % ('one', 'two')来对字符串进行格式化处理。新旧版本的差别参见 Ref.3。

下面是使用format函数进行格式化字符串的一般形式:

"{1} {0}! This is {2}. Today is {}/{},{}".format("world","hello","susan",d=12,m=10,y=1998)

### output
# hello world! This is susan. Today is 10/12, 1998

其中{}为格式占位符,调用format函数时使用参数替换并按占位符规定的格式格式化参数。

format函数参数的位参(positional argument)构成一个位参tuple,命名参数(keyword argument)构成一个dict,函数的参数传递方式一般都是位参先于命名参数,即format(位参,命名参数)

默认情况下,调用format函数将按先后顺序应用位参,命名参数则按照名称对号入座,我们可以在占位符中指定要应用的参数在位参列表中的索引值(起始索引值为0),如果索引值不小于位参个数将会触发out of range异常,这其实是tuple的索引溢出问题。

更详细的格式设置参见 Python document- Format Specification。

  • Ref

  1. how-to-use-string-formatters-in-python-3
  2. Format specification mini language
  3. Using % and .format() for great good!

你可能感兴趣的:(PYTHON使用FORMAT函数格式化字符串)