Skip to content

Python 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 −

  • The %% operator
  • The format()format() method
  • f-strings
  • Template Strings

The %% Operator

The %% operator is also known as the string formatting operator. It accepts a string on the left side and a tuple of values on the right side. The string contains one or more placeholders (%s%s, %d%d, %f%f, %c%c) that are replaced with the values from the tuple. Let’s look at an example.

strings.py
# define variables
name = "John"
age = 23
# print string
print("%s is %d years old." % (name, age))
strings.py
# define variables
name = "John"
age = 23
# print string
print("%s is %d years old." % (name, age))

Output:

command
C:\Users\Your Name> python strings.py
John is 23 years old.
command
C:\Users\Your Name> python strings.py
John is 23 years old.

In the above example, we have used %s%s and %d%d placeholders to insert the values of the variables into the string.

Here is a list of placeholders that can be used in the string −

SequencePlaceholderMeaning
1%c%cCharacter
2%s%sString conversion via str()str() prior to formatting
3%i%iSigned decimal integer
4%d%dSigned decimal integer
5%u%uUnsigned decimal integer
6%o%oOctal integer
7%x%xHexadecimal integer (lowercase letters)
8%X%XHexadecimal integer (UPPERcase letters)
9%e%eExponential notation (with lowercase ‘e’)
10%E%EExponential notation (with UPPERcase ‘E’)
11%f%fFloating-point real number
12%g%gThe shorter of %f%f and %e%e
13%G%GThe shorter of %f%f and %E%E

Examples of using the %% operator −

strings.py
# define variables
a = 5
b = 3.14
# print string
print("a is %d and b is %f" % (a, b))
strings.py
# define variables
a = 5
b = 3.14
# print string
print("a is %d and b is %f" % (a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.140000
command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.140000

Another example:

%d%d and %s%s placeholders to insert the values of the variables into the string.

strings.py
# define variables
name = "Ravi"
age = 19
# print string
print("%s is %d years old." % (name, age))
strings.py
# define variables
name = "Ravi"
age = 19
# print string
print("%s is %d years old." % (name, age))

Output:

command
C:\Users\Your Name> python strings.py
Ravi is 19 years old.
command
C:\Users\Your Name> python strings.py
Ravi is 19 years old.

In the above example, we have used %s%s and %d%d placeholders to insert the values of the variables into the string.

Other supported symbols and functionality are listed in the following table −

SequenceSymbolFunctionality
1**Width or precision
2--Left justification
3++Display the sign
4<sp><sp>Leave a blank space before a positive number
5##Add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.
600Pad from left with zeros (instead of spaces)
7%%’%%’ leaves you with a single literal ’%’
8(var)(var)Mapping variable (dictionary arguments)
9m.n.m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

Examples of using the %% operator −

%5d%5d is used to specify the width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is %5d and b is %5s" % (a, b))
strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is %5d and b is %5s" % (a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi

In the above example, we have used %5d%5d and %5s%5s placeholders to insert the values of the variables into the string. The number 55 is used to specify the width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example:

%05d%05d is used to specify the width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is %05d and b is %5s" % (a, b))
strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is %05d and b is %5s" % (a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi

In the above example, we have used %05d%05d and %5s%5s placeholders to insert the values of the variables into the string. The number 55 is used to specify the width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

Another example:

%1.2f%1.2f is used to specify the minimum total width of the field. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

strings.py
# define variables
pi = 3.141592653589793
# print string
print("The value of pi is %1.2f" % pi)
strings.py
# define variables
pi = 3.141592653589793
# print string
print("The value of pi is %1.2f" % pi)

Output:

command
C:\Users\Your Name> python strings.py
The value of pi is 3.14
command
C:\Users\Your Name> python strings.py
The value of pi is 3.14

In this example, we have used %1.2f%1.2f placeholder to insert the value of the variable into the string. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

Another example:

%20s%20s is used to specify the width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print("Hello, %20s." % name)
print("Hello, %-20s." % name)
strings.py
# define variables
name = "Ravi Kishan"
print("Hello, %20s." % name)
print("Hello, %-20s." % name)

Output:

command
C:\Users\Your Name> python strings.py
Hello,          Ravi Kishan.
Hello, Ravi Kishan         .
command
C:\Users\Your Name> python strings.py
Hello,          Ravi Kishan.
Hello, Ravi Kishan         .

In this example, we have used %20s%20s and %-20s%-20s placeholders to insert the values of the variables into the string. The number 2020 is used to specify the width of the field. The field will be filled with spaces if the value doesn’t use up the entire width. The -- sign is used to left-justify the value.

Another example:

%5.7s%5.7s is used to specify the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, %.5s." % name)
print("Welcome, %5.7s." % name)
strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, %.5s." % name)
print("Welcome, %5.7s." % name)

Output:

command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.
command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.

In this example, we have used %.5s%.5s and %5.7s%5.7s placeholders to insert the values of the variables into the string. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example:

%*.*s%*.*s is used to specify the minimum total width of the field.

strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, %*.*s." % (5, 7, name))
print("Welcome, %*.*s." % (-5, 7, name))
strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, %*.*s." % (5, 7, name))
print("Welcome, %*.*s." % (-5, 7, name))

Output:

command
C:\Users\Your Name> python strings.py
Welcome,   Ravi Ki.
Welcome, Ravi Ki.
command
C:\Users\Your Name> python strings.py
Welcome,   Ravi Ki.
Welcome, Ravi Ki.

In this example, we have used %*.*s%*.*s placeholder to insert the values of the variables into the string. The first number 55 is used to specify the minimum total width of the field. The second number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width. The -- sign is used to left-justify the value.

Another example:

The format() Method

format()format()

The format()format() method is used to perform string formatting. It takes the passed arguments, formats them, and places them in the string where the placeholders ({}{}) are.

format()format() is a method of the strstr class. Hence, it can be used with any string object. This is a built-in method in Python. Hence, it doesn’t require any import statement.

str.format()str.format()

The str.format()str.format() method is used to perform string formatting. It takes the passed arguments, formats them, and places them in the string where the placeholders ({}{}) are. this returns a new string object.

Let’s look at an example.

strings.py
# define variables
name = "Ravi"
age = 23
# print string
print("{} is {} years old.".format(name, age))
strings.py
# define variables
name = "Ravi"
age = 23
# print string
print("{} is {} years old.".format(name, age))

Output:

command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.

In the above example, we have used {}{} placeholders to insert the values of the variables into the string.

Here is a list of placeholders that can be used in the string −

SequencePlaceholderMeaning
1{}{}Insert the value in the placeholder
2{0}{0}Insert the value of the first argument in the placeholder
3{1}{1}Insert the value of the second argument in the placeholder
4{2}{2}Insert the value of the third argument in the placeholder
5{n}{n}Insert the value of the nth argument in the placeholder
6{m:n}{m:n}Insert the value of the nth argument in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.)
7{m:n.m}{m:n.m}Insert the value of the nth argument in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.)
8{m:n.mf}{m:n.mf}Insert the value of the nth argument in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
9{m:n.m%}{m:n.m%}Insert the value of the nth argument in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
10{m:n.mg}{m:n.mg}Insert the value of the nth argument in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
11{var}{var}Insert the value of the mapping variable (dictionary arguments) in the placeholder
12{var:n}{var:n}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of n digits after the decimal point (if appl.)
13{var:n.m}{var:n.m}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.)
14{var:n.mf}{var:n.mf}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign

Examples of using the format()format() method −

strings.py
# define variables
a = 5
b = 3.14
# print string
print("a is {} and b is {}".format(a, b))
strings.py
# define variables
a = 5
b = 3.14
# print string
print("a is {} and b is {}".format(a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.14
command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.14

Another example:

{0}{0} and {1}{1} placeholders to insert the values of the variables into the string.

strings.py
# define variables
name = "Ravi"
age = 23
# print string
print("{1} is {0} years old.".format(name, age))
strings.py
# define variables
name = "Ravi"
age = 23
# print string
print("{1} is {0} years old.".format(name, age))

Output:

command
C:\Users\Your Name> python strings.py
23 is Ravi years old.
command
C:\Users\Your Name> python strings.py
23 is Ravi years old.

In the above example, we have used {1}{1} and {0}{0} placeholders to insert the values of the variables into the string. The number 11 is used to specify the position of the second argument in the placeholder. The number 00 is used to specify the position of the first argument in the placeholder. The first argument is namename and the second argument is ageage. Hence, the value of ageage is inserted in the first placeholder and the value of namename is inserted in the second placeholder.

Another example:

{0:5d}{0:5d} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is {0:5d} and b is {1:5s}".format(a, b))
strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is {0:5d} and b is {1:5s}".format(a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi

In the above example, we have used {0:5d}{0:5d} and {1:5s}{1:5s} placeholders to insert the values of the variables into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example:

{0:05d}{0:05d} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is {0:05d} and b is {1:5s}".format(a, b))
strings.py
# define variables
a = 5
b = "Ravi"
# print string
print("a is {0:05d} and b is {1:5s}".format(a, b))

Output:

command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi

In the above example, we have used {0:05d}{0:05d} and {1:5s}{1:5s} placeholders to insert the values of the variables into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

Another example:

{0:1.2f}{0:1.2f} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

strings.py
# define variables
pi = 3.141592653589793
# print string
print("The value of pi is {0:1.2f}".format(pi))
strings.py
# define variables
pi = 3.141592653589793
# print string
print("The value of pi is {0:1.2f}".format(pi))

Output:

command
C:\Users\Your Name> python strings.py
The value of pi is 3.14
command
C:\Users\Your Name> python strings.py
The value of pi is 3.14

In this example, we have used {0:1.2f}{0:1.2f} placeholder to insert the value of the variable into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

Another example:

{0:20s}{0:20s} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 2020 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print("Hello, {0:20s}.".format(name))
print("Hello, {0:<20s}.".format(name))
strings.py
# define variables
name = "Ravi Kishan"
print("Hello, {0:20s}.".format(name))
print("Hello, {0:<20s}.".format(name))

Output:

command
C:\Users\Your Name> python strings.py
Hello, Ravi Kishan       .
Hello, Ravi Kishan       .
command
C:\Users\Your Name> python strings.py
Hello, Ravi Kishan       .
Hello, Ravi Kishan       .

In this example, we have used {0:20s}{0:20s} and {0:<20s}{0:<20s} placeholders to insert the values of the variables into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 2020 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width. The << sign is used to left-justify the value.

Another example:

{0:5.7s}{0:5.7s} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, {0:.5s}.".format(name))
print("Welcome, {0:5.7s}.".format(name))
strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, {0:.5s}.".format(name))
print("Welcome, {0:5.7s}.".format(name))

Output:

command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.
command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.

In this example, we have used {0:.5s}{0:.5s} and {0:5.7s}{0:5.7s} placeholders to insert the values of the variables into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example:

{0:*<5.7s}{0:*<5.7s} is used to specify the minimum total width of the field. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with ** if the value doesn’t use up the entire width. The << sign is used to left-justify the value.

strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, {0:*<5.7s}.".format(name))
print("Welcome, {0:*>5.7s}.".format(name))
strings.py
# define variables
name = "Ravi Kishan"
print("Welcome, {0:*<5.7s}.".format(name))
print("Welcome, {0:*>5.7s}.".format(name))

Output:

command
C:\Users\Your Name> python strings.py
Welcome, Ravi Ki.
Welcome, **Ravi Ki.
command
C:\Users\Your Name> python strings.py
Welcome, Ravi Ki.
Welcome, **Ravi Ki.

In this example, we have used {0:*<5.7s}{0:*<5.7s} and {0:*>5.7s}{0:*>5.7s} placeholders to insert the values of the variables into the string. The number 00 is used to specify the position of the first argument in the placeholder. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with ** if the value doesn’t use up the entire width. The << sign is used to left-justify the value.

Another example:

{var}{var} is used to specify the mapping variable (dictionary arguments) in the placeholder.

strings.py
# define variables
name = "Ravi Kishan"
age = 23
print("{name} is {age} years old.".format(name=name, age=age))
print("{name} is {age} years old.".format(**locals()))
strings.py
# define variables
name = "Ravi Kishan"
age = 23
print("{name} is {age} years old.".format(name=name, age=age))
print("{name} is {age} years old.".format(**locals()))

Output:

command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
Ravi Kishan is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
Ravi Kishan is 23 years old.

In this example, we have used {name}{name} and {age}{age} placeholders to insert the values of the variables into the string. The namename and ageage are the mapping variables (dictionary arguments) in the placeholder. namename and ageage are the keys of the dictionary. name=namename=name and age=ageage=age are the values of the dictionary. Hence, the value of namename is inserted in the first placeholder and the value of ageage is inserted in the second placeholder. The **locals()**locals() is used to unpack the dictionary.

Another example:

{name:5s}{name:5s} is used to specify the mapping variable (dictionary arguments) in the placeholder with the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
age = 23
print("{name:5s} is {age} years old.".format(name=name, age=age))
print("{name:5s} is {age} years old.".format(**locals()))
strings.py
# define variables
name = "Ravi Kishan"
age = 23
print("{name:5s} is {age} years old.".format(name=name, age=age))
print("{name:5s} is {age} years old.".format(**locals()))

Output:

command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
Ravi Kishan is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
Ravi Kishan is 23 years old.

In this example, we have used {name:5s}{name:5s} and {age}{age} placeholders to insert the values of the variables into the string. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width. The namename and ageage are the mapping variables (dictionary arguments) in the placeholder. namename and ageage are the keys of the dictionary. name=namename=name and age=ageage=age are the values of the dictionary. Hence, the value of namename is inserted in the first placeholder and the value of ageage is inserted in the second placeholder. The **locals()**locals() is used to unpack the dictionary.

Another example:

You can use format()format() to do formatting of a string to store it in a variable.

strings.py
# define variables
name = "Ravi Kishan"
age = 23
holders = "{name} is {age} years old."
intro = holders.format(name=name, age=age)
print(intro)
strings.py
# define variables
name = "Ravi Kishan"
age = 23
holders = "{name} is {age} years old."
intro = holders.format(name=name, age=age)
print(intro)

Output:

command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.

F-Strings

F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. F-strings are prefixed with ff or FF. The string literals can contain replacement fields surrounded by curly braces {}{}. Anything inside the curly braces is considered as an expression that will be evaluated at runtime. The result of the evaluated expression will be converted into a string and inserted into the string literal. Let’s look at an example.

strings.py
# define variables
name = "Ravi"
age = 23
# print string
print(f"{name} is {age} years old.")
strings.py
# define variables
name = "Ravi"
age = 23
# print string
print(f"{name} is {age} years old.")

Output:

command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.

In the above example, we have used {}{} placeholders to insert the values of the variables into the string.

Here is a list of placeholders that can be used in the string −

SequencePlaceholderMeaning
1{}{}Insert the value in the placeholder
2{var}{var}Insert the value of the mapping variable (dictionary arguments) in the placeholder
3{var:n}{var:n}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of n digits after the decimal point (if appl.)
4{var:n.m}{var:n.m}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.)
5{var:n.mf}{var:n.mf}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
6{var:n.m%}{var:n.m%}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
7{var:n.mg}{var:n.mg}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign

Examples of using the f-strings −

strings.py
# define variables
a = 5
b = 3.14
# print string
print(f"a is {a} and b is {b}")
strings.py
# define variables
a = 5
b = 3.14
# print string
print(f"a is {a} and b is {b}")

Output:

command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.14
command
C:\Users\Your Name> python strings.py
a is 5 and b is 3.14

Another example:

{a}{a} and {b}{b} placeholders to insert the values of the variables into the string.

strings.py
# define variables
name = "Ravi"
age = 23
# print string
print(f"{age} is {name} years old.")
strings.py
# define variables
name = "Ravi"
age = 23
# print string
print(f"{age} is {name} years old.")

Output:

command
C:\Users\Your Name> python strings.py
23 is Ravi years old.
command
C:\Users\Your Name> python strings.py
23 is Ravi years old.

In the above example, we have used {age}{age} and {name}{name} placeholders to insert the values of the variables into the string. The ageage and namename are the mapping variables (dictionary arguments) in the placeholder. ageage and namename are the keys of the dictionary. age=ageage=age and name=namename=name are the values of the dictionary. Hence, the value of ageage is inserted in the first placeholder and the value of namename is inserted in the second placeholder.

Another example:

{a:5d}{a:5d} is used to specify the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
a = 5
b = "Ravi"
# print string
print(f"a is {a:5d} and b is {b:5s}")
strings.py
# define variables
a = 5
b = "Ravi"
# print string
print(f"a is {a:5d} and b is {b:5s}")

Output:

command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is     5 and b is Ravi

In the above example, we have used {a:5d}{a:5d} and {b:5s}{b:5s} placeholders to insert the values of the variables into the string. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example:

{a:05d}{a:05d} is used to specify the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

strings.py
 
# define variables
a = 5
b = "Ravi"
# print string
print(f"a is {a:05d} and b is {b:5s}")
strings.py
 
# define variables
a = 5
b = "Ravi"
# print string
print(f"a is {a:05d} and b is {b:5s}")

Output:

command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi
command
C:\Users\Your Name> python strings.py
a is 00005 and b is Ravi

In the above example, we have used {a:05d}{a:05d} and {b:5s}{b:5s} placeholders to insert the values of the variables into the string. The number 55 is used to specify the minimum total width of the field. The field will be filled with 00 if the value doesn’t use up the entire width.

Another example:

{a:1.2f}{a:1.2f} is used to specify the minimum total width of the field. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

strings.py
# define variables
pi = 3.141592653589793
# print string
print(f"The value of pi is {pi:1.2f}")
strings.py
# define variables
pi = 3.141592653589793
# print string
print(f"The value of pi is {pi:1.2f}")

Output:

command
C:\Users\Your Name> python strings.py
The value of pi is 3.14
command
C:\Users\Your Name> python strings.py
The value of pi is 3.14

In this example, we have used {pi:1.2f}{pi:1.2f} placeholder to insert the value of the variable into the string. The number 11 is used to specify the minimum total width of the field. The number 22 is used to specify the number of digits to display after the decimal point.

Another example:

{a:20s}{a:20s} is used to specify the minimum total width of the field. The number 2020 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print(f"Hello, {name:20s}.")
print(f"Hello, {name:<20s}.")
strings.py
# define variables
name = "Ravi Kishan"
print(f"Hello, {name:20s}.")
print(f"Hello, {name:<20s}.")

Output:

command
C:\Users\Your Name> python strings.py
Hello, Ravi Kishan       .
Hello, Ravi Kishan       .
command
C:\Users\Your Name> python strings.py
Hello, Ravi Kishan       .
Hello, Ravi Kishan       .

In this example, we have used {name:20s}{name:20s} and {name:<20s}{name:<20s} placeholders to insert the values of the variables into the string. The number 2020 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width. The << sign is used to left-justify the value.

Another example:

{a:5.7s}{a:5.7s} is used to specify the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

strings.py
# define variables
name = "Ravi Kishan"
print(f"Welcome, {name:.5s}.")
print(f"Welcome, {name:5.7s}.")
strings.py
# define variables
name = "Ravi Kishan"
print(f"Welcome, {name:.5s}.")
print(f"Welcome, {name:5.7s}.")

Output:

command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.
command
C:\Users\Your Name> python strings.py
Welcome, Ravi.
Welcome, Ravi Ki.

In this example, we have used {name:.5s}{name:.5s} and {name:5.7s}{name:5.7s} placeholders to insert the values of the variables into the string. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Another example: xx, oo, XX, bb, nn, ee, EE, ff, FF, gg, GG, %% can be used to format the numbers.

strings.py
# define variables
a = 5
b = 3.14
print(f"a is {a:x} and b is {b:o}")
print(f"a is {a:X} and b is {b:b}")
print(f"a is {a:n} and b is {b:e}")
print(f"a is {a:N} and b is {b:E}")
print(f"a is {a:f} and b is {b:F}")
print(f"a is {a:g} and b is {b:G}")
print(f"a is {a:%} and b is {b:%}")
strings.py
# define variables
a = 5
b = 3.14
print(f"a is {a:x} and b is {b:o}")
print(f"a is {a:X} and b is {b:b}")
print(f"a is {a:n} and b is {b:e}")
print(f"a is {a:N} and b is {b:E}")
print(f"a is {a:f} and b is {b:F}")
print(f"a is {a:g} and b is {b:G}")
print(f"a is {a:%} and b is {b:%}")

Output:

command
C:\Users\Your Name> python strings.py
a is 5 and b is 5
a is 5 and b is 11
a is 5 and b is 3.140000e+00
a is 5 and b is 3.140000E+00
a is 5.000000 and b is 3.140000
a is 5 and b is 3.14
a is 500.000000% and b is 314.000000%
command
C:\Users\Your Name> python strings.py
a is 5 and b is 5
a is 5 and b is 11
a is 5 and b is 3.140000e+00
a is 5 and b is 3.140000E+00
a is 5.000000 and b is 3.140000
a is 5 and b is 3.14
a is 500.000000% and b is 314.000000%

In this example, we have used {a:x}{a:x}, {b:o}{b:o}, {a:X}{a:X}, {b:b}{b:b}, {a:n}{a:n}, {b:e}{b:e}, {a:N}{a:N}, {b:E}{b:E}, {a:f}{a:f}, {b:F}{b:F}, {a:g}{a:g}, {b:G}{b:G}, {a:%}{a:%}, and {b:%}{b:%} placeholders to insert the values of the variables into the string. xx, oo, XX, bb, nn, ee, EE, ff, FF, gg, GG, %% are used to format the numbers.

This table is the representation of the above example −

SequencePlaceholderMeaning
1{a:x}{a:x}Convert the value of aa to hexadecimal format
2{b:o}{b:o}Convert the value of bb to octal format
3{a:X}{a:X}Convert the value of aa to hexadecimal format
4{b:b}{b:b}Convert the value of bb to binary format
5{a:n}{a:n}Convert the value of aa to number format
6{b:e}{b:e}Convert the value of bb to exponential format
7{a:N}{a:N}Convert the value of aa to number format
8{b:E}{b:E}Convert the value of bb to exponential format
9{a:f}{a:f}Convert the value of aa to float format
10{b:F}{b:F}Convert the value of bb to float format
11{a:g}{a:g}Convert the value of aa to general format
12{b:G}{b:G}Convert the value of bb to general format
13{a:%}{a:%}Convert the value of aa to percentage format
14{b:%}{b:%}Convert the value of bb to percentage format
15{a:,.2f}{a:,.2f}Convert the value of aa to float format with comma as a thousand separator and 2 digits after the decimal point
16{a:,.2%}{a:,.2%}Convert the value of aa to percentage format with comma as a thousand separator and 2 digits after the decimal point
17{a:,.2e}{a:,.2e}Convert the value of aa to exponential format with comma as a thousand separator and 2 digits after the decimal point

Another example:

You can use the expression as a placeholder.

strings.py
# define variables
a = 9
b = 3
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")
strings.py
# define variables
a = 9
b = 3
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")

Output:

command
C:\Users\Your Name> python strings.py
9 + 3 = 12
9 - 3 = 6
command
C:\Users\Your Name> python strings.py
9 + 3 = 12
9 - 3 = 6

In this example, we have used {a} + {b} = {a+b}{a} + {b} = {a+b} and {a} - {b} = {a-b}{a} - {b} = {a-b} placeholders to insert the values of the variables into the string. The expression {a+b}{a+b} is used as a placeholder. The expression {a-b}{a-b} is used as a placeholder.

Another example:

You can use f-stringsf-strings to do formatting of a string to store it in a variable.

strings.py
# define variables
name = "Ravi Kishan"
age = 23
intro = f"{name} is {age} years old."
print(intro)
strings.py
# define variables
name = "Ravi Kishan"
age = 23
intro = f"{name} is {age} years old."
print(intro)

Output:

command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi Kishan is 23 years old.

Template Strings

Template strings provide a simpler way to do string formatting. Template strings are prefixed with $$ or ${}${}. The string literals can contain replacement fields surrounded by curly braces {}{}. Anything inside the curly braces is considered as an expression that will be evaluated at runtime. The result of the evaluated expression will be converted into a string and inserted into the string literal. Let’s look at an example.

strings.py
from string import Template
# define variables
name = "Ravi"
age = 23
# print string
print(Template("$name is $age years old.").substitute(name=name, age=age))
strings.py
from string import Template
# define variables
name = "Ravi"
age = 23
# print string
print(Template("$name is $age years old.").substitute(name=name, age=age))

Output:

command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.
command
C:\Users\Your Name> python strings.py
Ravi is 23 years old.

In the above example, we have used ${}${} placeholders to insert the values of the variables into the string.

Here is a list of placeholders that can be used in the string −

SequencePlaceholderMeaning
1${}${}Insert the value in the placeholder
2${var}${var}Insert the value of the mapping variable (dictionary arguments) in the placeholder
3${var:n}${var:n}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of n digits after the decimal point (if appl.)
4${var:n.m}${var:n.m}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.)
5${var:n.mf}${var:n.mf}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
6${var:n.m%}${var:n.m%}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
7${var:n.mg}${var:n.mg}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of m and n digits after the decimal point (if appl.) and the sign
8${var:5s}${var:5s}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.
9${var:5.7s}${var:5.7s}Insert the value of the mapping variable (dictionary arguments) in the placeholder with the minimum total width of the field. The number 55 is used to specify the minimum total width of the field. The number 77 is used to specify the maximum total width of the field. The field will be filled with spaces if the value doesn’t use up the entire width.

Conclusion

In this tutorial, we have learned about the string formatting techniques in Python. We have learned about the %% operator, format()format() method, f-strings, and template strings. We have also learned about the placeholders that can be used in the string. We have also learned about the formatting of numbers. Now you can use any of these techniques to format the strings in Python.

Was this page helpful?

Let us know how we did