Python uses the format() method to format strings
Formatting Strings with the Python format() Method
Python 3.0 introduced the format() method to handle complex string formatting more efficiently. This method was later ported to Python 2.6 and Python 2.7.
This built-in string class method provides sophisticated variable substitution and value formatting capabilities. This new formatting technique is considered more elegant. The general syntax of the format() method is as follows −
Syntax
str.format(var1, var2,...)
Return Value
This method returns a formatted string.
The string itself contains placeholders {}, into which the values of the variables are inserted.
Example 1
name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))
It will generate the following output .
my name is Rajesh and my age is 23 years
You can pass variables as keyword arguments to the format() method and use the variable names as placeholders in the string.
print ("my name is {name} and my age is {age} years".format(name="Rajesh", age=23))
You can also specify C-style formatting symbols. The only change is to use “:” instead of “%”. For example, use {:s} instead of %s and {:d} instead of %d.
name="Rajesh"
age=23
print ("my name is {:s} and my age is {:d} years".format(name, age))
Numbers can be formatted accordingly.
name="Rajesh"
age=23
percent=55.50
print ("my name is {:s}, age {:d} and I have scored {:6.3f} percent marks".format(name, age, percent))
This will produce the following output: −
my name is Rajesh, age 23 and I have scored 55.500 percent marks
Use the , , and ^ symbols within the placeholders to align the string (left, right, and center, respectively). Left alignment is the default.
name='TutorialsPoint'
print ('Welcome To {:>20} The largest Tutorials Library'.format(name))
print ('Welcome To {:<20} The largest Tutorials Library'.format(name))
print ('Welcome To {:^20} The largest Tutorials Library'.format(name))
This will produce the following output −
Welcome To TutorialsPoint The largest Tutorials Library
Welcome To TutorialsPoint The largest Tutorials Library
Welcome To TutorialsPoint The largest Tutorials Library
Similarly, to truncate a string, use a “.” in the placeholder.
name='TutorialsPoint'
print ('Welcome To {:.5} The largest Tutorials Library'.format(name))
It produces the following output −
Welcome To Tutor The largest Tutorials Library