Python - String Formatting Using format() Method
Python format() Method
Python 3.0, introduced format() method to str class for handling complex string formatting more efficiently. This method has since been backported to Python 2.6 and Python 2.7
This method of in-built string class provides ability to do complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant.
Syntax
The general syntax of format() method is as follows β
str.format(var1, var2,...)
Return value
The method returns a formatted string.
The string itself contains placeholders {} in which values of variables are successively inserted.
Example
name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))
It will produce the following output β
my name is Rajesh and my age is 23 years
String Formatting Using format() Method
You can use variables as keyword arguments to format() method and use the variable name as the placeholder 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. Only change is using ":" instead of %. For example, instead of %s use {:s} and instead of %d use (:d}
name="Rajesh"
age=23
print ("my name is {:s} and my age is {:d} years".format(name, age))
Precision Formatting Using format() Method
Precision formatting of numbers can be accordingly done.
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))
It will produce the following output β
my name is Rajesh, age 23 and I have scored 55.500 percent marks
String Alignment Using format() Method
String alignment is done with and ^ symbols (for left, right and center alignment respectively) in place holder. Default is left alignment.
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))
It 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
String Truncation Using format() Method
Similarly, to truncate the string use a "." in the place holder.
name='TutorialsPoint'
print ('Welcome To {:.5} The largest Tutorials Library'.format(name))
It will produce the following output β
Welcome To Tutor The largest Tutorials Library