Course
String Formatting
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
String Formatting
String formatting is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python's string concatenation operator doesn't accept a non-string operand. Hence, Python offers following string formatting techniques −
- Using % operator for substitution
- Using format() method of str class
- Using f-string syntax
- Using String Template class
Formatting Operator %
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's
printf()
family. Format specification symbols (%d %c %f %s etc) used in C language are used as placeholders in a string.Following is a simple example
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
It will produce the following output
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with
%
Other supported symbols and functionality are listed in the following table
In the following example, name is a string and age is an integer variable. Their values are inserted in the string at %s and %d format specification symbols respectively. These symbols are interpolated to values in a tuple in front % operator.
name="Rajesh"age=23print ("my name is %s and my age is %d years" % (name, age))
It will produce the following output
my name is Rajesh and my age is 23 years
You can specify width of an integer and float object. Here integer objects a,b and c will occupy width of 5 characters in formatted string. Additional spaces will be padded to left.
a=1b=11c=111print ("a=%5d b=%5d c=%5d" % (a, b, c))
It will produce the following output
a= 1 b= 11 c= 111
In following example, width of float variable is specified to have 6 characters with three digits after decimal point.
name="Rajesh"age=23percent=55.50print ("my name is %s, age %d and I have scored %6.3f percent marks" % (name, age, percent))
It will produce the following output
my name is Rajesh, age 23 and I have scored 55.500 percent marks
Width for a string can also be specified. Default alignment is right. For left alignment give negative sign to width.
name='TutorialsPoint'print ('Welcome To %20s The largest Tutorials Library' % (name, ))print ('Welcome To %-20s The largest Tutorials Library' % (name, ))
It will produce the following output
Welcome To TutorialsPoint The largest Tutorials LibraryWelcome To TutorialsPoint The largest Tutorials Library
Add a '. ' to the format to truncate longer string.
name='TutorialsPoint'print ('Welcome To %.5s The largest Tutorials Library' % (name, ))
It will produce the following output
Welcome To Tutor The largest Tutorials Library
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
Formatting Method format()
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. The general syntax of format() method is as follows
Syntax
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 1
name="Rajesh"age=23print ("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
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=23print ("my name is {:s} and my age is {:d} years".format(name, age))
Precision formatting of numbers can be accordingly done.
name="Rajesh"age=23percent=55.50print ("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 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 LibraryWelcome To TutorialsPoint The largest Tutorials LibraryWelcome To TutorialsPoint The largest Tutorials Library
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
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
f-string Formatting
The string starts with a '
f
' prefix, and one or more place holders are inserted in it, whose value is filled dynamically.name = 'Rajesh'age = 23fstring = f'My name is {name} and I am {age} years old'print (fstring)
It will produce the following output
My name is Rajesh and I am 23 years old
The f-string may contain expressions inside the
{}
placeholder.price = 10quantity = 3fstring = f'Price: {price} Quantity : {quantity} Total : {price*quantity}'print (fstring)
It will produce the following output
Price: 10 Quantity : 3 Total : 30
The placeholders can be populated by dictionary values.
user = {'name': 'Ramesh', 'age': 23}fstring = f"My name is {user['name']} and I am {user['age']} years old"print (fstring)
It will produce the following output
My name is Ramesh and I am 23 years old
The = character is used for self debugging the expression in f-string.
price = 10quantity = 3fstring = f"Total : {price*quantity=}"print (fstring)
It will produce the following output
Total : price*quantity=30
It is also possible to call a user defined function inside the f-string expression.
def total(price, quantity): return price*quantity
price = 10quantity = 3
fstring = f'Price: {price} Quantity : {quantity} Total : {total(price, quantity)}'print (fstring)
It will produce the following output
Price: 10 Quantity : 3 Total : 30
Python f-strings also support formatting floats with precision specifications, as done by
format()
method and string formatting operator %
name="Rajesh"age=23percent=55.50
fstring = f"My name is {name} and I am {age} years old and I have scored {percent:6.3f} percent marks"print (fstring)
It will produce the following output
My name is Rajesh and I am 23 years old and I have scored 55.500 percent marks
For string variable, you can specify the alignment just as we did with format() method and formatting operator %.
name='TutorialsPoint'fstring = f'Welcome To {name:>20} The largest Tutorials Library'print (fstring)
fstring = f'Welcome To {name:<20} The largest Tutorials Library'print (fstring)
fstring = f'Welcome To {name:^20} The largest Tutorials Library'print (fstring)
It will produce the following output
Welcome To TutorialsPoint The largest Tutorials LibraryWelcome To TutorialsPoint The largest Tutorials LibraryWelcome To TutorialsPoint The largest Tutorials Library
The f-strings can display numbers with hexadecimal, octal and scientific notation
num= 20fstring = f'Hexadecimal : {num:x}'print (fstring)
fstring = f'Octal :{num:o}'print (fstring)
fstring = f'Scientific notation : {num:e}'print (fstring)
It will produce the following output
Hexadecimal : 14Octal :24Scientific notation : 2.000000e+01
String Template Class
The Template class in string module provides an alternative method to format the strings dynamically. One of the benefits of Template class is to be able to customize the formatting rules.
The implementation of Template uses regular expressions to match a general pattern of valid template strings. A valid template string, or placeholder, consists of two parts: The $ symbol followed by a valid Python identifier.
You need to create an object of Template class and use the template string as an argument to the constructor.
Next call the substitute() method of Template class. It puts the values provided as the parameters in place of template strings.
Example
from string import Template
temp_str = "My name is $name and I am $age years old"tempobj = Template(temp_str)ret = tempobj.substitute(name='Rajesh', age=23)print (ret)
It will produce the following output
My name is Rajesh and I am 23 years old
We can also unpack the key-value pairs from a dictionary to substitute the values.
from string import Template
student = {'name':'Rajesh', 'age':23}temp_str = "My name is $name and I am $age years old"tempobj = Template(temp_str)ret = tempobj.substitute(**student)
print (ret)
It will produce the following output
My name is Rajesh and I am 23 years old
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.