Introduction

One of the most common tasks in any programming language is to output data to the user or to a file. Python offers a wide range of options for formatting output, but one of the most powerful and flexible is the format method. This method allows you to easily combine string literals and variables to create formatted strings that can be printed to the console or written to a file. In this tutorial, we will explore the various options available with the format method and see how it can be used to produce clean and polished output in your Python programs.

The format method in Python

  • The format() method was added in Python(2.6). 
  • Curly brackets {} are used to indicate the replacement fields.
  • Replacement field is the location within the string that will be replaced by the arguments in the format method.
  • Each replacement field contains
  • The arguments of the format function can be referenced in any order within the string.
  • We need to specify the index of the arguments in the replacement fields.
  • We can also use names of the keyword arguments in the replacement fields.
  • We can pass objects like dictionary elements, list elements as keyword arguments in format method.
  • We can then use these variable names in the replacement fields.
  • Another way of passing dictionary to format function is by using double-asterix (**) operator.
  • Code Sample : 

print('Hello!! {0} of {1}'.format('Scholars', 'Kolledge'))

# Output
# Hello!! Scholars of Kolledge

Prev. Tutorial : Using modulo operator

Next Tutorial : Using String methods