转载请注明出处
Python2.6+ 增加了str.format函数,用来代替原有的'%'操作符。它使用比'%'更加直观、灵活。下面详细介绍一下它的使用方法。
下面是使用'%'的例子:
"""PI is %f..." % 3.14159 # => 'PI is 3.141590...'"%d + %d = %d" % (5, 6, 5+6) # => '5 + 6 = 11'"The usage of %(language)s" % {"language": "python"} # => 'The usage of python'格式很像C语言的printf是不是?由于'%'是一个操作符,只能在左右两边各放一个参数,因此右边多个值需要用元组或者字典来包括,不能元组字典一起用,缺乏灵活度。
同样的例子用format方法改写:
"PI is {0}...".format(3.14159) # => 'PI is 3.14159...'"{0} + {1} = {2}".format(5, 6, 5+6) # => '5 + 6 = 11'"The usage of {language}".format(language = "Python") # => 'The usage of Python'

