Interview Kickstart has enabled over 21000 engineers to uplevel.
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:
The format function takes two parameters for formatting:
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.
Let’s now discuss how we can use the format function in python:
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 {}! ”
{}.format(value)
Whatever value we want to put in the placeholder {}, we pass as well using the standard syntax as shown above.
StrOne = "Hi, welcome to {}! "
fOne = StrOne.format("Interview Kickstart")
print(fOne)
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.
{}{}{}....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.
StrThree = "{}! Welcome to {}, {}! "
fThree = StrThree.format("Hello", "Interview Kickstart", "Richard")
print(fThree)
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:
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:
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:
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:
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:
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:
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:
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:
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!
-----------
Article contributed by Tanya Shrivastava
Attend our webinar on
"How to nail your next tech interview" and learn