上QQ阅读APP看书,第一时间看更新
Format method
A string's format method will inject its arguments into the string, replacing the fields defined by curly braces. A specific field can be defined either by the number (in this case, you just should keep arguments in the same order) or by using keywords. Here are some examples:
- The following example has no placement strategy and simple curly brackets:
>>> ‘Hello {} world and our blue {}'.format(‘beautiful', ‘planet')
'Hello beautiful world and our blue planet'
- The following example uses a numeric order (note the change of order and the repetition in the template):
>>> ‘{0} {2} {1} and our {2} {3}!'.format('Hello','World','Beautiful', 'Planet')
'Hello Beautiful World and our Beautiful Planet!'
- The following example uses keywords:
>>> ‘Hello {adj} world!'.format(adj='beautiful')
'Hello beautiful world!'
Personally, we prefer the last one, as it is explicit and prevents any mistakes with the position of the arguments. However, there is one more way to format strings on the go: via F-strings.