Different Methods For String Formatting In Python
Tags: python, programming, string, tutorial
Published: 2023-06-15 07:43:26

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:***

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

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

print("Hello, %s!" % 'Geeks')
```

***Output:***

```bash
Hello, Python
Hello, Geeks!
```

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

```python
print("I bought %d apples and %d oranges." %(6, 4))
```

***Output:***

```bash
I bought 6 apples and 4 oranges.
```

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

**Example - 2:**

```python
x = "car"
print("The dog %s down the %s." %('chased', x))
```

***Output:***

```bash
The dog chased down the car.
```

Using multiple format conversion types in a single string.

**Example - 3:**

```python
name = "Yashwant"
print("My %s %s bought the car worth $%d." %('friend', name, 15000))
```

***Output:***

```bash
My friend Yashwant bought the car worth $15000.
```

**Floating-point Precision using the % operator**

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

***Output:***

```bash
The length of land is: 85.526 metres
```

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.**

```python
print("The length of land is: %7.3f metres" %(85.52590))
print("The length of land is: %0.3f metres" %(85.52590))
```

***Output:***

```bash
The length of land is:  85.526 metres
The length of land is: 85.526 metres
```

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

> To know more, click [here](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting).

## 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:***

```python
# Formatting using format() method
print("Hey {}, Welcome {}.".format('Geeks', 'to GeekPython'))
```

***Output:***

```bash
Hey Geeks, Welcome to 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**

```python
print("{1}, there is a {2} {0} ahead.".format("error", "Caution", "Python"))
```

***Output:***

```bash
Caution, there is a Python error ahead.
```

**Example - 2:**

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

***Output:***

```bash
Python: 1991, Inventor: Guido, Version: 3.11
```

**Example - 3: Reusing the same value**

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

***Output:***

```bash
The first hurdle was easy, the second hurdle was intermediate but the third hurdle was very tough.
```

**Floating-point Precision with** `.format()` method

```python
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:***

```bash
The decimal number is: 54.123
The decimal number is: 23.547
```

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](https://docs.python.org/3/library/string.html#formatstrings).

## 3\. Using f-string (Literal String Interpolation):

Literal string interpolation, a new mechanism to format strings which were introduced in [PEP 498](https://www.python.org/dev/peps/pep-0498/).

These strings are called [**f-strings**](https://geekpython.in/f-string-in-python) 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:***

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

***Output:***

```bash
Hi, I am Sachin.
```

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

**Example - 1: Using multiple expressions**

```python
name = "Sachin"
x = 45
y = 12

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

***Output:***

```bash
Hi, I am Sachin and I run 456 metres daily.
```

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

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

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

***Output:***

```bash
My name is Sachin and I am saying Good luck.
```

**Example - 3: Using** `lambda` expression inside f-string

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

***Output:***

```bash
Using lambda function: 39
```

**Floating-point Precision in f-string**

***Syntax***

> **{ value : { width } . { precision } }**

```python
width = 5
precision = 7
value = 15.155245

print(f"The result is: {value:{width}.{precision}}")
```

***Output:***

```bash
The result is: 15.15525
```

> To know more, click [here](https://geekpython.in/f-string-in-python).

## 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)](https://www.python.org/dev/peps/pep-0292/)
    

**Take a look at the example for a better understanding:**

```python
from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name, y=greet))
```

***Output:***

```bash
Hello Sachin, Welcome here.
```

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

**Example - 1: Raising** `KeyError`

```python
from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name))
```

***Output:***

```bash
Traceback (most recent call last):
  ....
KeyError: 'y'
```

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

```python
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:***

```bash
Iron man was created by Stan Lee for Marvel in $country
```

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](https://docs.python.org/3/library/string.html#template-strings).

## Comparing

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

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

***Output:***

```bash
0.351656400016509
0.4346434000181034
0.1398726999759674
3.969239500002004
```

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](https://geekpython.in/convert-bytes-into-string)?

✅[Different ways to display images in Jupyter Notebook](https://geekpython.in/display-images-in-jupyter-notebook).

✅[What are context manager and the with statement in Python](https://geekpython.in/context-managers-and-python-with-statement)?

✅[Difference between the list insert(), append() and extend() methods](https://geekpython.in/insert-vs-append-vs-extend).

✅[How to access list values within a dictionary in Python](https://geekpython.in/access-list-values-within-the-dictionary)?

✅[What is the difference between sort and sorted in Python](https://geekpython.in/python-sort-vs-sorted)?

✅[The concept of constructor and initializer in Python](https://geekpython.in/init-vs-new).

---

**That's all for now**

**Keep Coding✌✌**