8.2.4 String’s format Method

  • f-strings were added to Python in version 3.6
  • Before that, formatting was performed with the string method format
  • f-string formatting is based on the format method’s capabilities
  • Call method format on a format string containing curly brace ({}) placeholders, possibly with format specifiers
  • Pass to the method the values to be formatted
  • If there’s a format specifier, precede it by a colon (:)
In [1]:
'{:.2f}'.format(17.489)
Out[1]:
'17.49'

Multiple Placeholders

  • format string may contain multiple placeholders
  • format method’s arguments correspond to the placeholders from left to right
In [2]:
'{} {}'.format('Amanda', 'Cyan')
Out[2]:
'Amanda Cyan'

Referencing Arguments By Position Number

  • Format string can reference specific arguments by their position in the format method’s argument list
In [3]:
'{0} {0} {1}'.format('Happy', 'Birthday')
Out[3]:
'Happy Happy Birthday'

Referencing Keyword Arguments

  • Can reference keyword arguments by their keys in the placeholders
In [4]:
'{first} {last}'.format(first='Amanda', last='Gray')
Out[4]:
'Amanda Gray'
In [5]:
'{last} {first}'.format(first='Amanda', last='Gray')
Out[5]:
'Gray Amanda'

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.