Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Format Function in Python

Last updated by Utkarsh Sahu on Sep 25, 2024 at 11:00 PM | Reading time: 9 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Format Function in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

A software developer deals with strings all the time, and handling complex strings efficiently is crucial. Python 3.0 recognizes the need for more efficiency in this area and therefore has introduced a method in its built-in string class. This method is the format() function, which we’ll cover in this article. 

If you’re a coding engineer preparing for your next technical interview prep for a Python-heavy software engineering role, this article will especially be helpful to you. 

We’ll learn:

  • What Is Python 3.0’s Format Function?
  • Use of the Format Function in Python
  • Example of the Format Function Python 
  • FAANG Interview Questions on Python Format Function 
  • FAQs on Python Format Function

What Is the Format Function in Python?

The format function takes two parameters for formatting: 

  • The value(s) to format.
  • Format specification on how the value(s) needs/need to be formatted.

The format specification involves using a placeholder position in which the desired value(s) will be passed. Placeholders are represented by curly brackets {}. We can use multiple placeholders and give multiple values to be put into them. Each placeholder must have a corresponding value given to be put into it, or else we’ll get an error.

After taking in the value and format specification as parameters, the format function then returns a formatted representation of the value entered based on the format specification provided. Internally, it calls  _format_() method of an object.

Syntax: string.format(valueA, valueB,…)

Here, the format method is called on the string, and values are passed into the format method, which modifies the string and places the values accordingly. The string contains the placeholders, and the values to put in the placeholders can be of different data types like integer, float, char, and string. They can also be variables.

How to Use the Format Function in Python

Let’s now discuss how we can use the format function in python:

Using a Single Formatter

Using a single formatter means we have a single placeholder and a single value to be put into it. And after putting the value in the placeholder, we will concatenate it with the string. So in the syntax we saw of the format function, the string is of the format:

Str = “Hi, welcome to {}! ”

Syntax: 

{}.format(value)

Whatever value we want to put in the placeholder {}, we pass as well using the standard syntax as shown above.

Example:

StrOne = "Hi, welcome to {}! "

fOne = StrOne.format("Interview Kickstart")

print(fOne)

Output:

Using Multiple Formatters

Using a multiple formatter means we have multiple placeholders {} and multiple values to be put into them. To avoid errors, we must make sure that for each placeholder present, the value to put in is being passed as an Index error occurs only when the string has an extra placeholder. We can add multiple placeholders {} in this way, and the values will be put in their respective placeholders {} in the order in which they’re written.

Syntax:

{}{}{}....format(valueA, valueB, valueC...)

Note that here the number of values passed should be equal to the number of curly braces {}, i.e., placeholders, in the string. The placeholders, by default, are usually assigned indices starting from 0 in order to put the right values in their corresponding placeholders. So by default, the first placeholder has index 0 and valueA goes in it, the second placeholder has index 1 and valueB goes in it, and so on.

Example:

StrThree = "{}! Welcome to {}, {}! "

fThree = StrThree.format("Hello", "Interview Kickstart", "Richard")

print(fThree)

Output:

Formatting Strings Using Escape Sequences

We can also use a combination of escape sequences to format strings. An escape sequence is a sequence of two or more characters that does not represent itself when it’s used inside a string. Instead, it represents something else entirely that would otherwise be difficult, if not impossible, to represent directly. In Python, like in many other languages, escape sequences start with a backslash. Here are some examples:

Formatters With Positional and Keyword Arguments

As we’ve seen, for empty placeholders, the values passed to the format function are replaced in order. Using positional and keyword arguments, it is also possible to print values into placeholders out of order. We can achieve this by mentioning the placeholder indices within the curly braces: {i}. So if we switch the order of passing valueA and valueB in the earlier example and use indices to guide where to store which value:

maxCG = 10

StrThree = "His CGPA is {1} out of {0}. He will {2}. "

fThree = StrThree.format(maxCG, 8.5, "graduate")

print(fThree)

The output will still be:

Type Specifying

We can be more precise about our specifications and include more parameters by specifying type:

In the case of float, we can also mention the precision, that is, the number of places after decimal we would like to print. When using the format function, we can specify the type by using a colon after the index inside the placeholder as {index: type specifier}, instead of using % symbol to specify the type. This will become clearer through an example:

Code:

name="Rohan"

marks= 94.5 

total=100

article ='a'

negative = -3

print('%s got %0.2f marks out of %u this time. He made %c mistake that contributed %d marks and reduced his score.' %(name, marks, total, article, negative))

print("{0:s} got {1:0.2f} marks out of {2:d} this time".format(name,marks, total))

Output:

Padding Substitutions or Generating Spaces

We can specify the alignment we want for the values that will replace the placeholders by using the following after the colon inside the placeholders:

We can also specify by how much we want to align something to the left/right/center. This will become clearer through an example:

Code:

name="Rohan"

marks= 94.5 

total=100

article ='a'

negative = -3

print("{} got {} marks out of {} this time".format(name,marks, total))

print("{0:>100} got {1:<40} marks out of {2:^500} this time".format(name,marks, total))

By default, strings are aligned to the left, and numbers are aligned to the right. So we have specified something different: right alignment for the string, left alignment for float and center alignment for int in our example.

Output:

Using a Dictionary for String Formatting

We can also use dictionaries to put its values into a string and use the key of the dictionary as an index inside the placeholder, which will tell us which value in the dictionary belongs to a placeholder. We use ** to unpack a dictionary’s values onto the string we want to format using it. So the format looks like “{keyone}...{keytwo}...”.format(**dictionaryName). This can be best illustrated through an example:

Code:

detailsDictionary= { "name":"Rohan","marks": 94.5 ,"total":100, "article":'a', "negative" :-3 }

print("{name} got {marks} marks out of {total} this time".format(**detailsDictionary))

Output:

Format Function Python Example

Let us now understand this with the help of an example dealing with different data types and the number of placeholders.

Code:

# Using a single formatter

# Value type int

StrOne = "There are only {} ways to do this."

fOne = StrOne.format(3)

print(fOne)

# Using multiple formatters

# Value types variable, float and string

maxCG = 10

StrThree = "His CGPA is {} out of {}. He will {}. "

fThree = StrThree.format(8.5, maxCG, "graduate")

print(fThree)

Output:

FAQs on Python Format Function 

Question 1: What are some applications of format function in python?

Answer: Format function is used to organize data, make it more readable by altering necessary parameters, such as size, alignment, etc.

Question 2: What happens if a string has an extra placeholder {} with no value passed for it in the format function?

Answer: If the number of placeholders {} is not equal to the number of values passed in the format function, we will get an error called IndexError. We know that the placeholders, by default, are usually assigned indices in order to put the right values in their corresponding placeholders. This is why when a placeholder at some index does not find a value to be put in it, an error is thrown (Index error).

Question 3: Can we merge and use these formatters?

Answer: Yes, we can merge these formatters and specify alignment, precision, type etc together as can be best shown by the following example:

Code:

name="Rohan"

marks= 94.5 

total=100

article ='a'

negative = -3

print("{0:>100s} got {1:<0.2f} marks out of {2:^500d} this time".format(name,marks, total))

detailsDictionary= { "name":"Rohan","marks": 94.5 ,"total":100, "article":'a', "negative" :-3 }

print("{name:>100s} got {marks:<0.2f} marks out of {total:^500d} this time".format(**detailsDictionary))

Output:

Recommended Reading

Check out our learn page for articles on Python, Java, and more:

To hone your tech interview prep, go to our blog and interview questions pages:

Are You Ready to Nail Your Next Coding Interview?

If you’re looking for guidance and help with getting your prep started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

-----------

Article contributed by Tanya Shrivastava

Last updated on: 
October 10, 2024
Author

Utkarsh Sahu

Director, Category Management @ Interview Kickstart || IIM Bangalore || NITW.

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Format Function in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image