Use of F-strings in Python

Fstrings in Python

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.
  • The main Use of F-strings in Python is F-strings are faster than the two most commonly used string formatting mechanisms, which are %-formatting and str.format(). 
  • Fstrings in Python 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:

Run
#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:

Run
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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription