Python format() function

Published February 15, 2022

Python's format() function is used for data formatting and variable substitution.  It enables efficient concatenation and handling of complex string formatting. In this post, we will learn how to format strings in Python


There are two ways in which strings can be formatted in Python:

  • Single formatter
  • Multiple formatter

Single formatter
To use a single formatter, we first place a single pair of curly braces [] at the beginning of a string and then call str.format().
This is a syntax for single formatting


 

{}.format(value),

 

Where value can be a string, integer, floating-point numeric  

Example of single formatter

print("{}, A computer science portal for geeks."
                .format("Hello World!!"))
str = "I love coding with Python {}"
print(str.format("Python"))
print("I have {} years experience !".format(18))


Output

Hello World!!, A computer science portal for geeks.
I love coding with Python Python
I have 18 years experience !

 

Multiple formatter
In multiple formatters, multiple pairs of curly braces are used  to format the string.   The syntax is as follows:
Syntax

: { } { } .format(value1, value2)


Where value 1 and value 2 can be integers, characters, variables, or floating-point constants.

An Example of  Multiple formatter
In the following example, several pairs of curly braces are used to format the string:
 

my_string = "{}, is the  {}  language for {}"
print(my_string.format("Python", "best", "web design"))


Output

Python, is the  best  language for web design

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

377 Views