Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Different Ways of String formatting in Python: Top 3 Methods

Updated on 04 October, 2022

8.51K+ views
8 min read

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

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

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.

Frequently Asked Questions (FAQs)

1. Which 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.

2. How 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.

3. Can 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.