Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconDifferent Ways of String formatting in Python: Top 3 Methods

Different Ways of String formatting in Python: Top 3 Methods

Last updated:
22nd Feb, 2021
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
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. 

Learn online data science courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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

Explore our Popular Data Science Certifications

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

Top Data Science Skills to Learn

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

Read our popular Data Science Articles

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

upGrad’s Exclusive Data Science Webinar for you –

ODE Thought Leadership Presentation

 

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 data science, check out IIIT-B & upGrad’s Executive PG Program 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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1Which formatting methods in Python 3 allows multiple substitutions and value formatting?

1. Python's built-in string format() method transforms a supplied string into a more useful output. The format() function in Python3 is one of the string formatting methods that allows for multiple substitutions as well as value formatting. The format() method uses positional formatting to concatenate items within a string.
2. The string can be formatted using numerous pairs of curly brackets. If another variable replacement is required in a long string, the second set of curly braces can be added and the second value passed into the procedure.
3. The format() function in Python accepts any number of parameters. However, it is primarily separated into the following two sorts of parameters.
a. Positional parameters are a list of parameters that can be retrieved by putting the parameter's index inside curly brackets (index).
b. Keyword parameters – This is a list of key=value parameters that can be accessed using the parameter's key inside curly braces.
4. The format() method returns a string that has been formatted. The format() function reads the type of arguments supplied to it and formats them according to the format codes in the string.

2How do you print without a newline in Python 3?

Add an extra argument to your print method in Python 3 to tell the computer that you don't want the next string to be on a new line. Consider the following scenario.
print('Welcome!', end = ')
In this case, any further print function will appear on the same line.

3Can we convert string to float in Python?

1. They are string objects if we acquire a float value through user input via the terminal as well as reading it from a file. As a result, we must explicitly convert them to float in order to conduct necessary operations like addition, multiplication, and so on.
2. The float() method in Python can be used to convert a string to a float. It's a built-in function for converting a floating-point number to an object. Internally, the float() function calls the __float__() function of the provided object.

Explore Free Courses

Suggested Blogs

Priority Queue in Data Structure: Characteristics, Types &#038; Implementation
57467
Introduction The priority queue in the data structure is an extension of the “normal” queue. It is an abstract data type that contains a
Read More

by Rohit Sharma

15 Jul 2024

An Overview of Association Rule Mining &#038; its Applications
142458
Association Rule Mining in data mining, as the name suggests, involves discovering relationships between seemingly independent relational databases or
Read More

by Abhinav Rai

13 Jul 2024

Data Mining Techniques &#038; Tools: Types of Data, Methods, Applications [With Examples]
101684
Why data mining techniques are important like never before? Businesses these days are collecting data at a very striking rate. The sources of this eno
Read More

by Rohit Sharma

12 Jul 2024

17 Must Read Pandas Interview Questions &amp; Answers [For Freshers &#038; Experienced]
58114
Pandas is a BSD-licensed and open-source Python library offering high-performance, easy-to-use data structures, and data analysis tools. The full form
Read More

by Rohit Sharma

11 Jul 2024

Top 7 Data Types of Python | Python Data Types
99373
Data types are an essential concept in the python programming language. In Python, every value has its own python data type. The classification of dat
Read More

by Rohit Sharma

11 Jul 2024

What is Decision Tree in Data Mining? Types, Real World Examples &#038; Applications
16859
Introduction to Data Mining In its raw form, data requires efficient processing to transform into valuable information. Predicting outcomes hinges on
Read More

by Rohit Sharma

04 Jul 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
82805
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

04 Jul 2024

Most Common Binary Tree Interview Questions &#038; Answers [For Freshers &#038; Experienced]
10471
Introduction Data structures are one of the most fundamental concepts in object-oriented programming. To explain it simply, a data structure is a par
Read More

by Rohit Sharma

03 Jul 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
70271
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

02 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon