Output Formatting in Python

In this article, we will learn various ways in python to format your output in Python. We mainly use two functions namely

  • format
  • f-strings

In-person I love f-strings because they were most adaptable. Every format can be written in both ways and we will see those in detail with codes using both the function. Let’s Start

Printing Variable In a String

For suppose we are using a variable and we want to print variable along with some string. We can do this with the following code

lucky_number = 2
#Format syntax
print("my lucky number is {}".format(lucky_number))
#f-string syntax
print(f"my lucky number is {lucky_number}")
my lucky number is 2
my lucky number is 2

For a string, {} this is used as a place holder. you will call format as an attribute and inside it, you will write a variable name. whereas In f-string before the start quote of string you put f. Inside the string, you will use curly braces and insides braces itself you will write variable names.

More than one variable

For suppose you have to print three variables in a string. You can see the below code.

item = 'Dark Fantasy'
shop = 'My Stores'
price = 24.45
print("the price of {0} in {1} is {2}".format(item,shop,price))
print(f"the price of {item} in {shop} is {price}")
the price of Dark Fantasy in My Stores is 24.45
the price of Dark Fantasy in My Stores is 24.45

Note: since there are three arguments, you can use 0,1,2 only. Try jumbling those and see the changes in output.
One more way in format function is using a dictionary like a syntax.

print("the price of {i} in {s} is {p}".format(i=item,s=shop,p=price))

This is the same as the previous one but we have specific names rather than 0,1,2 e.t.c, but the output is the same.

Floating Point with Precision

Let’s Get to Real Content. How to format floats like %10.2f in c language if you have any previous experience

“Result : {value: {width}.{precision}}”

width is the number of places it uses as a canvas. width works only if the width value is greater than total digits(including after decimal point). precision is exactly the number of digits it will show after the decimal point. precision works only for floats. Let’s see some examples

num = 23.45678345
print("The number is:{0:10.4f}".format(num))
print(f"The number is:{num:{0}.{9}}")
value = 300.0987654

#Printing only 3 digits after decimal point

#Increasing width changes the canvas lenght you can observe in output
The number is:   23.4568
The number is:23.4567834

Please note that in the zero in starting in lines 9 and 10refers to the first argument inside the format function.
Feel free to share your thoughts and doubts in the below comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *