BlogsDope image BlogsDope

Different Ways to format a string in Python

July 11, 2020 PYTHON STRING 6756

In this article, we are going to learn different ways of formatting a string in Python. We will go through five different approaches in detail with examples. So, let’s get started.

% Operator


This is the old method of formatting a string in Python. You must be familiar with it if you have experience with the C programming language. Let’s take an example and see how this works.

name = "Virat Kohli"
score = 90
print("%s scored %d runs in the last match." % (name, age))

Output

name = "Virat Kohli"
score = 90
print("%s scored %d runs in the last match." % (name, age))

In the above example, the % operator follows a conversion type, for example, s for string, d for int, f for floating point. We have a variable name of string type and a variable score of int type. Therefore, we have used %s and %d, respectively. The argument specifiers, %s and %d, are placed at positions where we want to put the value of variables. A tuple containing the required variables is then followed by a % operator and the format string, i.e., % (name, age). Note that when you have a single variable, you can put it without tuple.

import math

pi = math.pi
print("The value of pi is %f" % pi)
print("The value of pi is %.2f" % pi)

Output

The value of pi is 3.141593
The value of pi is 3.14

The %f displays numbers up to six decimal places. %.xf displays up to x decimal places. The above example shows the value of pi upto 2 decimal places.

We can pass a mapping key to refer to the substitution by name. In this case, instead of a tuple, we need to pass a dictionary with keys as the substitution names. Let’s see an example.

name = "Virat Kohli"
score = 90
print(
    "%(name)s scored %(score)d runs in the last match." % {"name": name, "score": score}
)

Output

Virat Kohli scored 90 runs in the last match.

You do not have to remember the order of the substitutions when passing a mapping key.

This is an old way of formatting strings. The code looks messy, and it is a bit difficult to understand it as well.

format()


This method was introduced in Python 3. The syntax is str.format(var1, var2, …). We can pass any data type, for example, string, list, int, etc. Consider the following example to understand it.

name = "Virat Kohli"
score = 90
string = "{} scored {} runs in the last match"
print(string.format(name, score))

Output

Virat Kohli scored 90 runs in the last match

This is the same example as the previous one but has used the format() method. Put the placeholder {} where you want to insert the value of a variable. The variables are then passed as arguments in the format() method. We can also explicitly number placeholders. The number 0 is the first value that you pass in the format() method, 1 is the second value, and so on. Let's look at the following example.

name = "Virat Kohli"
score = 90
string = "{0} scored {1} runs in the last match. {0} is one of the best players."
print(string.format(name, score))

Output

Virat Kohli scored 90 runs in the last match. Virat Kohli is one of the best players.

The variable name is the first argument and the variable score is the second argument, so {0} returns “Virat Kohli”, and {1} returns 90.

We can pass keywords in placeholders as well. The value of a keyword is set within format(). Let’s see an example.

name = "Virat Kohli"
score = 90
string = (
    "{name} scored {score} runs in the last match. {name} is one of the best players."
)
print(string.format(name=name, score=score))

Output

Virat Kohli scored 90 runs in the last match. Virat Kohli is one of the best players.

We can provide different formatting options using a colon in the placeholder. For example, :<, :> and :^ are used to left align, right align and center align the result respectively.

The following example pads a zero in the tens place of a number.

for i in range(1, 11):
    print("Iteration no. {i:02}".format(i=i))

Output

Iteration no. 01
Iteration no. 02
Iteration no. 03
Iteration no. 04
Iteration no. 05
Iteration no. 06
Iteration no. 07
Iteration no. 08
Iteration no. 09
Iteration no. 10

The following example displays the binary representation of numbers from 0 to 5 with padding of zero.

for i in range(0, 6):
    print("Binary Representation of {i} = {i:03b}".format(i=i))

Output

Binary Representation of 0 = 000
Binary Representation of 1 = 001
Binary Representation of 2 = 010
Binary Representation of 3 = 011
Binary Representation of 4 = 100
Binary Representation of 5 = 101

For more on format specifiers, look at the official documentation.

f-strings


f-string or formatted string literal is another great way to format strings introduced in Python 3.6. These are easier, compact, and faster. As the name suggests, these are string literals starting with the letter f. The placeholder {} can contain any Python expression. Let’s see some examples to understand these better.

name = "Virat Kohli"
score = 90
print(f"{name} scored {score} runs in the last match")

Output

Virat Kohli scored 90 runs in the last match

As you can see, this code displays the same string obtained above in the examples of the % operator and the format() method. However, it is more convenient and readable.

Here is another example.

for i in range(0, 6):
    print(f"The square of the number {i} is {i**2}")

Output

The square of the number 0 is 0
The square of the number 1 is 1
The square of the number 2 is 4
The square of the number 3 is 9
The square of the number 4 is 16
The square of the number 5 is 25

The first placeholder contains an integer variable, and the second contains a mathematical expression.

The strings are formatted in the same way the format() method does, i.e., using a colon in {}.

Consider the following example that center aligns the content (i) in the placeholder within the given area. :^ specifies that the content will be center aligned and the number 10 specifies that the available area is 10 characters and so the content will be center aligned within this available area.

for i in range(0, 6):
    print(f"The square of the number{i:^10}is {i**2}")

Output

The square of the number    0     is 0
The square of the number    1     is 1
The square of the number    2     is 4
The square of the number    3     is 9
The square of the number    4     is 16
The square of the number    5     is 25

The above code center aligns the variable i within the given area of 10 characters.

Template


The Template class from the string module allows us to format strings as well. This, however, does not allow format specifiers. So, format the string beforehand. It uses $ operator for substitutions. The syntax is $identifier.  Consider the following example.

from string import Template

t = Template("$name scored $score runs in the last match")
print(t.substitute(name="Virat Kohli", score=90))

Output

Virat Kohli scored 90 runs in the last match

The constructor Template takes a template string (a string having $-based substitutions). The t.substitute() method performs the substitutions and returns the string.

Concatenation


We can also format strings using the + operator. It becomes difficult to format a string using this way because you have to open and close strings at different places. Moreover, you have to cast other data types to string type. Let’s see.

name = "Virat Kohli"
score = 90
print(name + " scored " + str(score) + " runs in the last match.")

Output

Virat Kohli scored 90 runs in the last match.

In conclusion, when the string is already formatted, you can use the Template class. Otherwise, if the Python version is 3.6 or more, prefer f-strings because they are simpler and faster.


Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).