Different Ways of String formatting in Python: Top 3 Methods

String formatting is an essential feature in the programming languages to format or insert user-specified values and positions in the strings. The C language had one way to do this which you might be familiar with if you have some experience with C language. Python, however, supports not 1, not 2, but 3 different ways to do string formatting. Each way has its advantages and disadvantages that we’ll be seeing in this tutorial. We’ll also see which of the 3 methods is the most used and efficient way. 

By the end of this tutorial, you will know the following:

  • Different ways of string formatting
  • Their usage with examples
  • Which way is the most preferred

Different Ways of String Formatting

Python has been getting multiple updates to improve string formatting. Let’s go through each of them one by one.

Method 1: C Style String Formatting

Python includes the old way of string formatting by using special characters for each data type. This good old string formatting method was adopted from the C language and is still very effective. A string format specifier “%” followed by a dedicated character for each data type is used for formatting the strings.

Let’s go over a small example to understand this:

num = 8
name = “pinkman”
print(“Name is %s and number is %d” %( name, num))

 

#Output
>> “Name is pinkman and number is 8”

 

As you see, the format specifier %s was used to format the string name and %d was used to format the integer num. Similarly, there is a format specifier for a float as well. Let’s check that out as well. 

 

num = 4.32
lis = [1, 3, 5]
print(“list is %s and float is %f” %(lis, num))

 

#Output
>> list is [1, 3, 5] and float is 4.320000

 

In the above example, I use the %f format specifier to format the float value. Two things to notice here. One, the float value is printed as 4.320000 and not just 4.32. Why so? This is because Python by default uses a 6 decimal point accuracy for floats. Second, I printed a list using the string format specifier. It doesn’t mean that %s format specifier can take in any data type. It just converts it into string and prints it. So the list that is printed is essentially a string and not a list.

Alright, so how to specify how many decimal point accuracy is required?

print(“list is %s and float with 2 point accuracy is %.2f” %(lis, num))

 

#Output
>> list is [1, 3, 5] and float is 4.32

 

Another point to notice here is that we need to give the variables in the order in which they are used in the string. If the order is changed then the output is set to be affected accordingly. An alternative for not requiring us to give the variables in the right order every time is to use string formatting in a slightly different way.

print(“list is %(a)s and float is %(b)f” %{“b”: num, “a”: lis})

 

#Output
>> list is [1, 3, 5] and float is 4.320000

 

And as you see, this is very cumbersome to write.

So just to summarise, the 3 most frequently used format specifiers are:

  1. %s for strings
  2. %d for integers
  3. %.<decimal accuracy>f for floats

Method 2:  New Style String Formatting

Python 3 introduced a better way to do string formatting by using a format() method on strings. A placeholder is used by placing curly brackets and the format method contains the variables that need to be put in those positions in the string. Let’s have a look at a small example to understand this.

name = “skyler”
print(“Hi, my name is {}”.format(name))

 

#Output
>> Hi, my name is skyler

 

This is much better than the old-style formatting that we saw above. The curly braces act as a placeholder for the variable name which contains a string. Note, that with the format method we don’t need to specify the data type of the variable as we did in the old-style formatting.

An example with numbers as well:

num = 3
int = 4.34
name = “jessy”

print(“Hi, my name is {}, number is {} and float is {}”.format(name, num, int))

 

#Output
>> Hi, my name is jessy, number is 3 and float is 4.34

Neat! As you see, it needs the variables to be passed to the format method in the order in which they were used in the string. Another way to use the format method by not requiring us to pass all the variables in the right order:

print(“Hi, my name is {name}, number is {num} and float is {int}”.format(int=int, num=num , name=name))

 

#Output
>> Hi, my name is jessy, number is 3 and float is 4.34

In the above example, we see that when the variables are explicitly mentioned in the placeholders then the need to pass them to format method in the correct order is no longer required. 

We can also pass the position of the variable in the placeholders to keep a better track of them.

print(“Hi, my name is {0}, number is {1} and float is {2}”.format(name, num, int))

 

#Output
>> Hi, my name is jessy, number is 3 and float is 4.34

Method 3: Using F-Strings

Introduced in Python 3.6, f-strings is the easiest and most efficient way to do string formatting.  These are also called formatted string literals. They use the literal f at the beginning of the string to tell python to treat it as a formatted string. The placeholders contain the actual variables that need to be put in that position.

Let’s have a look at an example.

name = “heisenberg”
bill = 100.43print(f”The name is {name} and the bill is {bill}”)

 

#Output
>> The name is heisenberg and the bill is 100.43

This was quite easy. Moreover, we can also put expressions directly instead of variables.

 

a = 5
b = 8

print(f”The sum is {a+b})

 

#Output
>> The sum is 13

We can also call the functions directly and get their output in the string literals.

 

print(f”The name is {name.upper()})

 

#Output
>> The name is HEISENBERG

 

Moreover, we can use the f strings to directly return the value from functions as well.

def combiner(name, age, money):
return f”{name} is of age {age} and has salary {money}”

 

Saul Goodman is of age 45 and has salary 2000000

 

As we see, when we pass the functions directly to the placeholders, it calls the functions and directly places the outputs in the curly braces. Clearly, this method of String Formatting is the most efficient one and easy to write. 

Checkout: Python Interview Questions & Answers

Before you go

String formatting is a regular task and the way Python introduced the format method and f strings make it very easy for people working with Python. The f-strings are the most used and preferred way of working with the string formatting as it makes it very easy to write and maintain. Plus, it makes the code more Pythonic as well! Under the hood, the f strings use the __format__ protocol. The f literal is just syntactic sugar that python offers its users to make it easier for us to write string formatting.

If you are curious to learn about Python, Data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN DATA SCIENCE
ENROLL NOW @ UPGRAD

Leave a comment

Your email address will not be published.

×