F-strings in Python

What the F*** is F-string in Python

Python provides several ways to format strings. These different ways have their own advantages and disadvantages.
Python 3.6 and above come with another method of string formatting (formally termed as string interpolation) known as f-strings” or Formatted string literals PEP 498.
I knew about it recently while working on a Kattis problem with a friend.  I found it interesting and worth sharing it here.
Off The Topic Discussion. Here in my country, Bhutan, today is the Teachers’ Day. I have my best wishes to all the teachers all over the globe to keep enlightening the world. Happy Teachers’ Day!
Happy Teachers' Day!
Happy Teachers’ Day! (This amazing picture is from yellow.bt)
Getting back to the topic, the idea behind f-strings is to make string interpolation simpler. With them, you don’t have to explicitly write lengthy boring str.format(). With f-strings, all you need to do is type f. 
Let me show you an example of how traditional string interpolation using str.format() works.
Say you want a program that takes two strings as inputs and prints it.
first_name = input()
last_name = input()
# Using str.format()
print('My name is: {} {}'.format(first_name, last_name))

Output

Sonam
Dargay
My name is: Sonam Dargay

Let us do the same using f-string.

first_name = input()
last_name = input()

#using f-string
print(f'my name is {last_name} {first_name}')

It gives the same output.

To make the power of f-string more convincing let us look into how we can format an abstract data structure, say dictionary.

Using str.format()

dic = {'name': 'Sonam', 'age': 21}
print('My name is: {} and I am {} years old.'.format(dic['name'], dic['age']))

Output

My name is: Sonam and I am 21 years old.

Using f-string

dic = {'name': 'Sonam', 'age': 21}
print(f'my name is: {dic["name"]} and I am {dic["age"]} years old.')

Output

The program gives the same output as the previous.

NOTE: You may also like to read:

Differences between sort() and sorted() in Python

What to take from this piece?

From the above cases, one can deduce that that, f-strings are:

  1. More readable,
  2. More concise,
  3. Less prone to error, and
  4. Faster.
%d bloggers like this: