DEV Community

Cover image for Different Methods For String Formatting In Python
Sachin
Sachin

Posted on • Originally published at geekpython.in

Different Methods For String Formatting In Python

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:

# Use of the modulo operator for string formatting
name = "Python"
print("Hello, %s" % name)

# ----------------OR--------------

print("Hello, %s!" % 'Geeks')
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Python
Hello, Geeks!
Enter fullscreen mode Exit fullscreen mode

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

print("I bought %d apples and %d oranges." %(6, 4))
Enter fullscreen mode Exit fullscreen mode

Output:

I bought 6 apples and 4 oranges.
Enter fullscreen mode Exit fullscreen mode

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

Example - 2:

x = "car"
print("The dog %s down the %s." %('chased', x))
Enter fullscreen mode Exit fullscreen mode

Output:

The dog chased down the car.
Enter fullscreen mode Exit fullscreen mode

Using multiple format conversion types in a single string.

Example - 3:

name = "Yashwant"
print("My %s %s bought the car worth $%d." %('friend', name, 15000))
Enter fullscreen mode Exit fullscreen mode

Output:

My friend Yashwant bought the car worth $15000.
Enter fullscreen mode Exit fullscreen mode

Floating-point Precision using the % operator

print("The length of land is: %2.3f metres" %(85.52590))
Enter fullscreen mode Exit fullscreen mode

Output:

The length of land is: 85.526 metres
Enter fullscreen mode Exit fullscreen mode

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.

print("The length of land is: %7.3f metres" %(85.52590))
print("The length of land is: %0.3f metres" %(85.52590))
Enter fullscreen mode Exit fullscreen mode

Output:

The length of land is:  85.526 metres
The length of land is: 85.526 metres
Enter fullscreen mode Exit fullscreen mode

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:

# Formatting using format() method
print("Hey {}, Welcome {}.".format('Geeks', 'to GeekPython'))
Enter fullscreen mode Exit fullscreen mode

Output:

Hey Geeks, Welcome to GeekPython.
Enter fullscreen mode Exit fullscreen mode

Let's see some examples

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

Example - 1: Using index-based positioning

print("{1}, there is a {2} {0} ahead.".format("error", "Caution", "Python"))
Enter fullscreen mode Exit fullscreen mode

Output:

Caution, there is a Python error ahead.
Enter fullscreen mode Exit fullscreen mode

Example - 2:

print("Python: {x}, Inventor: {y}, Version: {z}".format(x=1991,
                                                        y="Guido",
                                                        z=3.11))
Enter fullscreen mode Exit fullscreen mode

Output:

Python: 1991, Inventor: Guido, Version: 3.11
Enter fullscreen mode Exit fullscreen mode

Example - 3: Reusing the same value

print("The first {obj} was easy, the second {obj} was intermediate "
      "but the third {obj} was very tough.".format(obj="hurdle"))
Enter fullscreen mode Exit fullscreen mode

Output:

The first hurdle was easy, the second hurdle was intermediate but the third hurdle was very tough.
Enter fullscreen mode Exit fullscreen mode

Floating-point Precision with .format() method

print("The decimal number is: {0:1.3f}".format(54.123456, 23.5466))
print("The decimal number is: {1:1.3f}".format(54.123456, 23.5466))
Enter fullscreen mode Exit fullscreen mode

Output:

The decimal number is: 54.123
The decimal number is: 23.547
Enter fullscreen mode Exit fullscreen mode

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:

name = "Sachin"
print(f"Hi, I am {name}.")
Enter fullscreen mode Exit fullscreen mode

Output:

Hi, I am Sachin.
Enter fullscreen mode Exit fullscreen mode

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

Example - 1: Using multiple expressions

name = "Sachin"
x = 45
y = 12

print(f"Hi, I am {name} and I run {8*(x + y)} metres daily.")
Enter fullscreen mode Exit fullscreen mode

Output:

Hi, I am Sachin and I run 456 metres daily.
Enter fullscreen mode Exit fullscreen mode

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

def write(name, say):
    return f"My name is {name} and I am saying {say}."

output = write("Sachin", "Good luck")
print(output)
Enter fullscreen mode Exit fullscreen mode

Output:

My name is Sachin and I am saying Good luck.
Enter fullscreen mode Exit fullscreen mode

Example - 3: Using lambda expression inside f-string

print(f"Using lambda function: {(lambda x: x*13)(3)}")
Enter fullscreen mode Exit fullscreen mode

Output:

Using lambda function: 39
Enter fullscreen mode Exit fullscreen mode

Floating-point Precision in f-string

Syntax

{ value : { width } . { precision } }

width = 5
precision = 7
value = 15.155245

print(f"The result is: {value:{width}.{precision}}")
Enter fullscreen mode Exit fullscreen mode

Output:

The result is: 15.15525
Enter fullscreen mode Exit fullscreen mode

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:

from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name, y=greet))
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Sachin, Welcome here.
Enter fullscreen mode Exit fullscreen mode

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

Example - 1: Raising KeyError

from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name))
Enter fullscreen mode Exit fullscreen mode

Output:

Traceback (most recent call last):
  ....
KeyError: 'y'
Enter fullscreen mode Exit fullscreen mode

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

from string import Template

character = "Iron man"
name = "Stan Lee"
country = "USA"

my_str = Template("$x was created by $y for Marvel in $country")
print(my_str.safe_substitute(x=character, y=name))
Enter fullscreen mode Exit fullscreen mode

Output:

Iron man was created by Stan Lee for Marvel in $country
Enter fullscreen mode Exit fullscreen mode

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.

import timeit

# Using % operator
mod = timeit.timeit("""
char = 'Iron man' 
name = 'Stan Lee' 
'%s was created by %s' %(char, name)
""", number=1000000)
print(mod)

# Using format() method
format_method = timeit.timeit("""
char = 'Iron man' 
name = 'Stan Lee'
'{} was created by {}.'.format(char, name)
""", number=1000000)
print(format_method)

# Using f-string
fst = timeit.timeit("""
char = 'Iron man' 
name = 'Stan Lee'
f'{char} was created by {name}.'
""", number=1000000)
print(fst)

# Using Template Class
tcl = timeit.timeit("""
from string import Template
char = 'Iron man'
name = 'Stan Lee'
my_str = Template("$x was created by $y.")
my_str.substitute(x=char, y=name)""", number=1000000)
print(tcl)
Enter fullscreen mode Exit fullscreen mode

Output:

0.351656400016509
0.4346434000181034
0.1398726999759674
3.969239500002004
Enter fullscreen mode Exit fullscreen mode

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✌✌

Top comments (0)