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.
SyntaxThe 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.
Examplename="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 yearsString 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 marksString 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 LibraryString 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
python_string_formatting.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4