Formatted Printing
Consider the following program:
When this code is executed with Sachin as the input, we get the following output:
This looks messy as there is an unwanted space after the name. This is a formatting issue. Python provides some useful tools to format text the way we want.
f-strings
The first method we will look at is called formatted string literals, or f-strings for short. Let us jump into the syntax:
When this code is executed with Sachin as the input, we get the following output:
The messy formatting has been corrected. Let us take a closer look at the string inside the print command:
This is called a formatted string literal, or f-string. The f in front of the string differentiates f-strings from normal strings. An f-string is an object that, when evaluated, results in a string. The value of the variable name is inserted in place of {name} in the f-string.
Two things are important for f-strings to work correctly:
- The
fin front of the string. - The curly braces
{}enclosing the variable.
Let us see what happens if we miss one of these two:
This will give the output:
Let us now look at a few other examples:
For l = 4, b = 5, the output is:
Notice that line-4 has an expression — l * b — inside the curly braces, not just a variable. f-strings allow any valid Python expression inside the curly braces. If the f-string has some {expression} in it, the interpreter will substitute the value of the expression.
Another example:
For an input of 3, this will give the following result:
The \t is a tab character. It has been added before and after the =. Remove both tabs and run the code to observe any changes in the output.
Till now, we have used f-strings within the print statement. Nothing stops us from using them to define other string variables:
Try to guess what this code is doing.
format()
Another way to format strings is by using a string method called format().
In the above string, the curly braces {} will be replaced by the value of the variable name. Another example:
Let us now print the multiplication table using format:
The output will be identical to the one we saw with f-strings.
Format Specifiers
Consider the following code:
This gives the following output:
There are too many numbers after the decimal point. Format specifiers are a way to solve this problem:
This gives the following output:
Example
Let us print the marks of three students in a class with right alignment:
This produces the output:
The 10.2f in {marks_1:10.2f} specifies that the float should be rounded to two decimal places, with a minimum width of 10.
Another example with integers:
This gives the following output:
Points to Note
dstands for integer.5dafter:specifies a minimum column width of 5.