String Formatting Comparison: format() | Percent | f-string

Summary: f-string is more readable and easier to implement than % and .format() string formatting styles. Furthermore, using f-strings is suggested for Python 3.6 and above while .format() is best suited for Python 2.6 and above. Versions prior to Python 2.6 only provide % option for string formatting. In terms of speed, % is the fastest string formatting style.

Overview

Problem: Compare the different string formatting styles in Python i.e. % Vs .format() Vs Formatted String Literal/f-strings.

Solution Overview: There are 4 ways of formatting a string in Python as of now. These are

  1. % formatting
  2. str.format()
  3. f-string (String Literal)
  4. Template Strings

Example: Let us have a look at the following example where we have used all the four ways of string formatting:

from string import Template

name = "FINXTERS!"
print('1. Hello %s' % name)
print('2. Hello {}'.format(name))
print(f"3. Hello {name}")
temp = Template("4. Hello $name")
print(temp.substitute(name=name))

Output

1. Hello FINXTERS!
2. Hello FINXTERS!
3. Hello FINXTERS!
4. Hello FINXTERS!

So, from the above example, we see that all the string formatting types produce the same output. Having said that, we now have a lot of questions to address. Some of these questions include :

  • What is the difference between each string formatting method?
  • Which string formatting method should be preferred and in which situation should it be preferred?

To learn more about the usage of each Python string formatting, follow this blog tutorial. However, in this article, we will learn and primarily focus on the key differences between the first three string formatting methods as mentioned in our problem statement. Without further delay let us dive into the key differences.

Before you dive deeper into these methods, let’s make it stick with this quick exercise:

Exercise: Add a second string variable firstname and insert it into each output!

Syntax Difference

The following table depicts the difference in syntax between each string formatting method:

% formattingstr.format()f-Strings
Syntax:
<string with format specifier>%variable
Syntax:
<string with placeholder> .format(value1, value2…)
Syntax:
f'<string with its placeholder>’
example:
name = “FINXTERS!”
print(‘1. Hello %s’ % name)
example:
name = “FINXTERS!”
print(‘2. Hello {}’.format(name)) 
example:
name = “FINXTERS!”
print(f’3. Hello {name}’)

Version And Compatibility Difference

The following table depicts the difference between each string formatting style in terms of their compatibility in different Python versions.

% formattingstr.format()f-Strings
1. Introduced in the initial/first release of Python.   1.  Introduced in Python 2.6. 1.  Introduced in Python 3.6.
2. Can be used in any version of Python. However, it is not a recommended style of string formatting for Python 2.6 and above. 2.  It can be used in Python 2.6 and above. However, it will raise a syntax error if used in versions prior to Python 2.6.2.  Can be used only in Python 3.6 and above. It will raise a Syntax Error if used in versions prior to Python 3.6

Functional Difference

% formattingstr.format()f-Strings
% is an operator known as modulo operator which allows us to format a string object in Python. It is an inbuilt method that allows us to format a string object in Python. f-string is a literal string in Python, with 'f' as a prefix and contains expressions inside braces.
Complex syntax and can either accept a variable or a tuple.
Please have a look at Example 1 given below, to get a better view of this concept.
Being a newer and improved string formatting style it is more versatile and easy to use than %. It has a simpler syntax and uses similar syntax whether you need to accept a string variable or a tuple.
Please have a look at Example 1 given below, to get a better view of this concept.
It uses an even simpler syntax since .format() can get tedious, especially when used with long strings. Please have a look at Example 1 given below, to get a better view of this concept.

It is a more powerful option of string formatting on account that it allows us to embed expressions within the string itself. Please have a look at Example 2 given below to get a better view of this concept.

Let us compare the string formatting styles based on their ease of implementation using a few examples:

Example 1

name = 'Finxter Shubham'
tup = (1, 2, 3)

# Different syntax for printing a string and tuple
print("Name: %s" % name)
print("Tuple: %s" % (tup,))

# same syntax to print both string and tuple
print("Name: {}".format(name))
print("Tuple: {}".format(tup))

# even more readable and easier syntax
print(f'Name: {name}')
print("Tuple: " f'{tup}')

Output

Name: Finxter Shubham
Tuple: (1, 2, 3)
Name: Finxter Shubham
Tuple: (1, 2, 3)
Name: Finxter Shubham
Tuple: (1, 2, 3)

f-strings lead to cleaner code because their syntax enables the value of an expression to be placed directly inside a string. The following example shows how to easily embed expressions within f-strings:

Example 2

# The number of units per player
units = {}
units['Alice'] = 10
units['Bob'] = 15
x = 'Alice'
y = 'Bob'
print(f'{x} has {units["Bob"] - units["Alice"]} units less than {y}')

Output

Alice has 5 units less than Bob

To find out, how you can perform the above operation in the .format() string formatting method – click here!

► Now, let us have a look at an example that depicts how easily we can use positional arguments in case of .format() and f-strings but how hideous it becomes while doing the same using % formatting.

Example 3

tu = (100, 500, 300)
print('{0} {2} {1}'.format(*tu))
print(f'{tu[0]}, {tu[2]}, {tu[1]}')

# using % formatting
print('%(a)s %(c)s %(b)s' % {'a': 100, 'b': 500, 'c': 300})

Output

100 300 500
100, 300, 500
100 300 500

► Another advantage of the new string formatting methods over % string formatting is :- new styles can take object properties whereas % cannot do so. Let us have a look at the following code to see the working principle behind this concept:

class Finxter(object):
    def __init__(self, a, b):
        self.x = a
        self.y = b


a = Finxter(2, 3)
print("\nUsing .format():")
print('Value1 = {0}\nValue2 = {1}'.format(a.x, a.y))
print("\nUsing f-string:")
print(f'Value1={a.x}\nValue2={a.y}')
print("\nNot possible using %")

Output

Using .format():
Value1 = 2
Value2 = 3

Using f-string:
Value1=2
Value2=3

Not possible using %

Speed/Performance Difference

Though speed and performance are not the primary metrics when it comes to string formatting yet we must discuss the difference between them in terms of performance since there might be a rare situation where speed is also a criteria in the program.

Let us have a look at the following program to discover who wins the race in terms of speed:

import timeit

print('.format() Speed:', timeit.timeit("'{}{}{}'.format(0.5, 1.5, 'SPEED TEST!')"))
print('% Speed:', timeit.timeit("'%s%s%s' % (0.5, 1.5, 'SPEED TEST!')"))
print('f-string Speed:', timeit.timeit("f'{0.5}{1.5}{\"SPEED TEST!\"}'"))

Output

.format() Speed: 1.615438
% Speed: 1.2333532999999999
f-string Speed: 1.2435527000000004

Therefore, we see that % (modulo) string formatting style wins the performance race!

Use Case That Suits A Specific String Formatting Style

From the above discussions, we can easily deduce the following:

  • If you are using any version prior to Python 2.6 stick with the old % (modulo) string formatting method.
  • If you are using Python 2.6 or above then using the .format() string formatting method is a better option.
  • If you are using Python 3.6 or above, the best option for string formatting is f-string.

If you are confused regarding the version of Python you are working upon, then you might want to have a look at this tutorial.

Conclusion

In this article, we discussed the key differences between %, str.format(), and f-strings based on numerous factors along with their examples. I hope after reading this article you can compare and contrast the differences between each string formatting style with ease. Though the examples used in the above article are very basic ( for a better understating of the concept), the same contrasts also hold true in the case of complex situations.

If you enjoyed reading this article, please subscribe and stay tuned for more interesting articles!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!