How to use f-string In Python
This method was introduced in Python 3.6 version. This is much easier than using a format specifier or a format() method. The f-strings are expressions that are evaluated in the runtime and are formatted by the __format__() method. For formatting a string using the f-string, the formatting expression must be written in quotes preceded by ‘f’/’F’.
Syntax : f “<text> {placeholder} <text>” or F”<text> {placeholder} <text>”
Example 1:
The name and age are variables. They can be formatted and printed with the help of f-string by placing the variable in the appropriate placeholders. The placeholders are just the curly braces found within the texts.
Python3
name = "Rinku" age = 20 print (f "Hi! my name is {name} and my age is {age}" ) |
Hi! my name is Rinku and my age is 20
Example 2:
Expressions can also be evaluated and displayed using this f-string method.
Python3
a = 5 b = 6 print (F "Addition : {a+b}" ) print (F "Subtraction : {a-b}" ) print (F "Multiplication : {a*b}" ) print (F "Division without roundoff : {a/b}" ) print (F "Division with roundoff : {round(a/b,3)}" ) |
Addition : 11 Subtraction : -1 Multiplication : 30 Division without roundoff : 0.8333333333333334 Division with roundoff : 0.833
Example 3:
Even functions can be called from the f-string placeholders. A function to evaluate the expression a2 + 3b2 + ab is defined and called within the placeholder.
Python3
# f function to evaluate expression def exp_eval(a, b): ans = (a * a) + ( 3 * (b * b)) + (a * b) return ans # values to be evaluated a = 2 b = 4 # formatting print (f "The expression a**2+3b**2+(a*b) = {exp_eval(a,b)}" ) |
The expression a**2+3b**2+(a*b) = 60
How to use string formatters in Python ?
The output displayed as a result of a program should be organized in order to be readable and understandable. The output strings can be printed and formatted using various ways as listed below.
- Using print()
- Using format specifiers.
- Using format() method.
- Using formatted string literal (f-string).
This article covers the first three methods given above.