Fstrings in Python

Fstrings in Python

PEP 498 proposed to add a new string formatting mechanism: Literal String Interpolation. In this PEP, such strings will be referred to as “f-strings”, taken from the leading character used to denote such strings, and standing for “formatted strings”. 

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces. 

f-Strings Python programming language

String Format

  • Python supports multiple ways to format text strings. These include %-formatting , str.format() , and string.template. All of them have their on advantages but in addition have it’s own disadvantages which creates problem during practice like we can not concat string and integers implicitly.
  • F-strings are faster than the two most commonly used string formatting mechanisms, which are %-formatting and str.format(). 
  • F-strings provide a concise, readable way to include the value of Python expressions inside strings.

Example: 

  • w=70 , print(‘My weight is ‘ + w + ‘kgs’)
    • TypeError: Can’t convert ‘int’ object to str implicitly  

  • w=70 #using f-strings
    • print(f”My weight is {w} kgs.”) 
    • My weight is 70 kgs.
f-strings in python

Code #1:

#f-strings 
w=70 
print(f“My weight is {w} kgs.”
webs=‘PrepInsta’
print(f{webs} is for Prepsters.”)
Output:

My weight is 70 kgs.

PrepInsta is for Prepsters.

Code #2:

PI=22/7 
print(f“Value of pi is {PI:.50F}
#OR 
print(f“Value of pi is {22/7:.50f})
Output:

Value of pi is 3.14285714285714279370154144999105483293533325195312

Value of pi is 3.14285714a285714279370154144999105483293533325195312