Follow

Follow
4 Ways of String Formatting in Python - Guide

4 Ways of String Formatting in Python - Guide

Sachin Pal's photo
Sachin Pal
·Feb 6, 2022·

7 min read

Play this article

Table of contents

  • Introduction
  • 1. Using % (modulo) Operator:
  • 2. Using format() method:
  • 3. Using f-string (Literal String Interpolation):
  • 4. String Template Class
  • Comparing
  • Conclusion

In this tutorial, we gonna discuss the 4 types of string formatting techniques in Python.

We gonna walk through all the 4 types of methods and learn the use cases so that you can learn the fundamentals of different 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 are aware of arithmetic operators in Python then you would know that we use this operator to get the remainder of the dividend.

The same operator we use in the oldest style of string formatting. Modulo (%) operator is also known as "String-formatting" or "String-interpolation" operator.

Here's an example:

# An example to demonstrate the use of the operator for string formatting
name = "Python"
print("Hello, %s" %name)

# ----------------OR--------------
print("Hello, %s!" %'Geeks')

Output:

output.png

We use format specifiers to tell Python that you have to substitute the given value in that specific position.

I used the "%s" format specifier to insert the string "Python" on 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))

Output:

example-1_ Output.png

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

Output:

example-2 output.png

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

Output:

example-3 output.png

Floating-point Precision using the % operator

print("The length of land is: %2.3f metres" %(85.52590))

Output:

floating-point output.png

Now you might wonder, why I 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))

Output:

floating-point output2.png

Here, the first print statement gets padded with whitespace. You can notice the difference in both the results.

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', 'here'))

Output:

format_output.png

Let's see some examples

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

Example - 1: Using index-based positioning

print("{1}, there's a {2} {0} ahead".format("error", "Caution", "Python"))

Output:

index-positioning output.png

Example - 2:

print("Python: {x}, Inventor: {y}, Version: {z}".format(x=1991, 
                                                        y="Guido",
                                                        z=3.9))

Output:

example_2 output.png

Example - 3: Reusing the object

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

Output:

example_3 output.png

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

Output:

floating-point-precision-using-format.png

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 would be

{ [ 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 decimal point

  • f - is the type of format code

Here are the common type 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 the example:

name = "Sachin"
print(f"Hi, I am {name}.")

Output:

f-string example output.png

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 {4*(x + y)} metres daily.")

Output:

f-string example 1 output.png

Example - 2: Using f-string inside the function

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

output = write("Sachin", "Good luck")
print(output)

Output:

f-string example 2 output.png

Example - 3: Using lambda expression inside f-string

print(f"Using lambda function: {(lambda x: x*13)(3)}")

Output:

f-string example 3 output.png

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}}")

Output:

f-string float precision output.png

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

Output:

template class output.png

Here "x" and "y" are the placeholders prefixed by "$" substituted by the values of 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))

Output:

template class KeyError.png

The above code snippet raised a KeyError because I didn't specify mapping for 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))

Output:

template class safe_substitute.png

Here I didn't specify mapping for "$country" and still I didn't get any error because I used the "safe_substitute" method.

To know more, click here.


Comparing

from string import Template

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

# Using % operator

print("%s was created by %s for Marvel in %s." %(character, name, country))

# Using format() method

print("{} was created by {} for Marvel in {}.".format(character, name, country))

# Using f-string

print(f"{character} was created by {name} for Marvel in {country}.")

# Using Template Class

my_str = Template("$x was created by $y for Marvel in $z.")
print(my_str.substitute(x=character, y=name, z=country))

Output:

comparing output.png


Conclusion

So far we conclude that all the ways performed for string formatting are different from each other, each of them has a unique style of formatting.

New techniques and ways were created to counter the lack of efficiency or ability to handle complex formatting.

Since we have seen all the types of string formatting and compared them, we can choose the best and most efficient string formatting technique for us.


That's all for now

Keep Coding✌✌

Did you find this article valuable?

Support Sachin Pal by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this