Printing variables using f-strings in python

Printing the values of variables is required. It may serve as an output for user to read or for the developers who are debugging their code. Sometimes we need the printed output to be easier to understand and not just a set of variable values. Using formatted string literals or f-strings is by far the most intuitive way to print out variables along with intermittent text. The simple example of printing using f-strings is as follows:

a = 2
b = 3
print(f'The value of a is {a}, and the value of b is {b}.')
The value of a is 2 and the value of b is 3.

 

The syntax involves a 'print()' statement that starts with 'f' before the quotation marks into which our print statement is written. The variable whose values are to be printed are written inside the curly brackets.

Using fstrings the print() statement becomes more human readable as compared to the string format method. You may read about this in the python documentation here. In fact, I could never remember how to use the string format method and hence used another method of just separating the text and variables to be printed by a comma which again, is not a very convenient way to write print statements even though is more intuitive way. 

We can also use f-strings to print out the variable name and its value by adding '=' in front of the variable name as follows:

name = 'Harry'
surname = 'Potter'
age = 24
print(f'Following are the details of the student:\n {name=} \n {surname=}\n {age=}')
Following are the details of the student:
 name='Harry' 
 surname='Potter'
 age=24

There are some more functionalities in f-strings such as defining the least amount of space each variable would take and rounding up the numbers to specific digits. For simplicity, we will not write about them here. You can read about it on the python documentation page.


Popular posts from this blog

Principal Coordinate analysis in R and python

Principal Coordinate Analysis (PCoA) in R