You are currently viewing 4 Ways of String Formatting in Python – Guide

4 Ways of String Formatting in Python – Guide

This article will go over the four different types of string formatting techniques in Python.

We’ll go over all four types of methods and their applications so we can understand the fundamentals of various string formatting techniques.

Introduction

What is string formatting? Well, we can call it the process in which we inject things dynamically into the string and return the formatted version of that string.

There are 4 ways to perform string formatting that are all different from each other:

  • Using % Operator (“old style”)
  • Using format() string method
  • Using String literals (f-string)
  • Using String Template class

We will see the fundamentals of the ways mentioned above.

1. Using % (modulo) Operator

This way of formatting the strings, use the % (modulo) operator. If you’re familiar with Python’s arithmetic operators, you’ll recognize that we use this operator to calculate the remainder of the dividend.

The same operator we use in the oldest style of string formatting. Modulo (%) operators are also referred to as “String-formatting” or “String-interpolation” operators.

Here’s an example:

Output:

We use format specifiers to tell Python that the given value must be substituted in that specific position.

We used the "%s" format specifier to insert the string "Python" in that specific position.

We have some format specifiers that we use commonly:

  • %s – for string
  • %d – for integers
  • %f – for floating-point values
  • %b – for binary format
  • %e – for floating-point exponent

Let’s look at the examples showing different formatting conditions.

Example 1: Formatting the integer values

Output:

We can insert multiple strings as well as we can use variables to insert objects in the string.

Example 2:

Output:

Using multiple format conversion types in a single string.

Example 3:

Output:

Floating-point Precision using the % operator

Output:

Now you might wonder, why we used %2.3f.

Floating-point numbers use an x.yf format, where x is a minimum number of digits in a string and yf represents how many digits have to display after the decimal point.

If the whole number doesn’t have the specified number of digits then it might be padded with whitespace.

Output:

The first print statement is padded with whitespace in this case. There is a distinction between the two outcomes.

To know more, click here.

2. Using format() method

This method is introduced to get rid of the % operator formatting. This method is suitable for handling complex string formatting more efficiently.

str.format() method is pretty simple and fast as compared to "%" operator formatting and is introduced in Python3.

In this technique of formatting, formatters work by putting the placeholders enclosed by pair of curly braces "{ }" and calling the str.format() method.

Syntax:

“String goes { } and here { }”.format(“here” , “also”)

Here’s an example:

Output:

Let’s see some examples

We can use index-based positioning to insert the object into the string

Example – 1: Using index-based positioning

Output:

Example – 2:

Output:

Example – 3: Reusing the same value

Output:

Floating-point Precision with .format() method

Output:

We have seen floating-point precision using the % operator where the format was x.yf but here the case is a bit different.

Here, the Syntax is

{ [ index ] : [ width ] . [ precision ] [ type ] }

If we breakdown {0:1.3f} this then:

  • 0 – is the index value
  • 1 – is the width
  • 3 – is the precision or no. of digits to be displayed after the decimal point
  • f – is the type of format code

Here are the common types that we can use with format code:

  • “d” – for integers
  • “f” – for floating-point numbers
  • “s” – for string
  • “e” – for floating-point in an exponent format
  • “o” – for octal numbers
  • “x” – for hexadecimal numbers
  • “b” – for binary numbers

To know more, click here.

3. Using f-string (Literal String Interpolation)

Literal string interpolation, a new mechanism to format strings which were introduced in PEP 498.

These strings are called f-strings because of their leading character "f" that is used to denote the string and here, f – stands for “formatted” string.

f-strings are string literals that are prefixed by the letter "f".

f-string uses the same format specifier mini-language that is used for str.format().

Here’s an example:

Output:

Let’s see the use case of the f-strings in different conditions:

Example – 1: Using multiple expressions

Output:

Example – 2: Using an f-string inside the function

Output:

Example – 3: Using lambda expression inside f-string

Output:

Floating-point Precision in f-string

Syntax

{ value : { width } . { precision } }

Output:

To know more, click here.

4. String Template Class

In this method, we use "$" before the placeholders which are enclosed with { } curly braces.

In this style of formatting, we use the Template class to make a template and once the template has been created then we can perform substitution by calling two methods:

  • substitute(): This method returns a new string which results when the values of mapping are substituted for the placeholders in the Template. If there are placeholders that are not present in the mapping, a KeyError will be raised.
  • safe_substitute(): This is similar to the substitute() method, except that KeyErrors are never raised (due to placeholders missing from the mapping). When a placeholder is missing, the original placeholder will appear in the resulting string. (Source)

Take a look at the example for a better understanding:

Output:

Here "x" and "y" are the placeholders prefixed by "$" substituted by the values of the mapping "name" and "greet".

Example – 1: Raising KeyError

Output:

The above code snippet raised a KeyError because we didn’t specify the mapping for the placeholder "$y". But if we use "safe_substitute()" method then it will not raise KeyError.

Example – 2: Using safe_substitute method

Output:

We didn’t specify the mapping for "$country" here, but there was no error because we used the safe_substitute method.

To know more, click here.

Comparing

Consider the following example in which we are comparing the execution time of the code snippets of different formatting methods.

Output:

We obtained the time required by each code snippet to complete one million executions, and thus we can conclude that the f-string was relatively fast, taking nearly 0.14 seconds, which is significantly less than other methods.

Conclusion

We can conclude that all of the methods used for string formatting are distinct from one another, with each having its own formatting style.

To compensate for the lack of efficiency or ability to handle complex formatting, new methods were developed over time.

We can choose the best and most efficient string formatting technique for us now that we have seen and compared all of the different types of string formatting.


🏆Other articles you might like if you like this article

How to convert bytes into a string in Python?

Different ways to display images in Jupyter Notebook.

What are context manager and the with statement in Python?

Difference between the list insert(), append() and extend() methods.

How to access list values within a dictionary in Python?

What is the difference between sort and sorted in Python?

The concept of constructor and initializer in Python.


That’s all for now

Keep Coding✌✌