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:

  1. 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'
  1. 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!'
  1. 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. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.56.251