4 Ways of String Formatting in Python — Guide

Sachin Pal
8 min readAug 4, 2022

--

String formatting in Python
Source: Author(GeekPython)

This tutorial will discuss the 4 types of string formatting techniques in Python.

We will walk through all 4 types of methods and learn the use cases to learn the fundamentals of different string formatting techniques.

Introduction

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

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. The modulo(%) operator is also known as the "String-formatting" or "String-interpolation" operator.

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

# ----------------OR--------------
print("Hello, %s!" %'Geeks')
Output
Source: Author(GeekPython)

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

I used the "%s" format specifier to insert the string "Python" in that particular 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- Formatting the integer values
Source: Author(GeekPython)

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- Using both variable and string to format the string
Source: Author(GeekPython)

We are 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- Using variable, string and integer simultaneously to format the string
Source: Author(GeekPython)

Floating-point precision using the % operator

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

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 yf represents how many integers have to display after the decimal point.

If the whole number doesn't have the specified number of digits, 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 Precision
Source: Author(GeekPython)

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 the 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 compared to "%" operator formatting and is introduced in Python3.

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

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

# Formatting using format() method

print("Hey {}, Welcome {}....".format('Geeks', 'here'))
Output- Using format() method
Source: Author(GeekPython)

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's a {2} {0} ahead".format("error", "Caution", "Python"))
formatting string using index-based positioning
Source: Author(GeekPython)

Example — 2:

print("Python: {x}, Inventor: {y}, Version: {z}".format(x=1991, 
y="Guido",
z=3.9))
Output- key:value based formatting
Source: Author(GeekPython)

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- Reusing the object
Source: Author(GeekPython)

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 with .format() method
Source: Author(GeekPython)

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

Here, the Syntax would be

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

If we breakdown {0:1.3f} 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 is 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 is a new mechanism to format strings introduced in PEP 498.

These strings are called f-strings because of their leading character "f", which 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 used for str.format().

name = "Sachin"
print(f"Hi, I am {name}.")
Output- Using f-string
Source: Author(GeekPython)

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- Using multiple expressions
Source: Author(GeekPython)

Example — 2: Using the 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- Using the f-string inside the function
Source: Author(GeekPython)

Example — 3: Using lambda expression inside f-string

print(f"Using lambda function: {(lambda x: x*13)(3)}")
Output- Using lambda expression inside f-string
Source: Author(GeekPython)

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- Floating-point Precision in f-string
Source: Author(GeekPython)

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 when the mapping values are substituted for the placeholders in the Template. If placeholders 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- String Template Class
Source: Author(GeekPython)

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- Raising KeyError
Source: Author(GeekPython)

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

Example — 2: Using the 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- Using the safe_substitute method
Source: Author(GeekPython)

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

To know more, click here.

Comparing

We are printing the same string by using a different formatting style.

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 all four types of string formatting technique
Source: Author(GeekPython)

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.

That's all for now.

Keep Coding✌✌

Originally published at https://geekpython.in.

--

--

Sachin Pal
Sachin Pal

Written by Sachin Pal

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.

No responses yet