Efficient way of string formatting - Python 3’s f-string

Before diving into f-string introduced in Python 3.6, let’s talk about the other two string formatting options available in Python.

Option 1: % formatting

Note: % formatting is not recommended by Python docs now.

How to use it?

Example 1.1:

>>> name =  "Naveen"
>>> lastname = "Kumar"
>>> "Hello, %s %s" %(name, lastname)
'Hello, Naveen Kumar'

Why not great?

  • not readable
  • with more arguments, things get messy

Option 2: str.format

How to use it?

Example 2.1:

>>> name =  "Naveen"
>>> lastname = "Kumar"
>>> "Hello, {} {}".format(name, lastname)
'Hello, Naveen Kumar'

We can also use indexing to reference variables in any order.

Example 2.2:

>>> name =  "Naveen"
>>> lastname = "Kumar"
>>> "My lastname is: {1} and my first name is: {0}".format(name, lastname)
'My lastname is: Kumar and my first name is: Naveen'

Why not great?

  • better than % formatting but still very verbose when dealing with multiple parameters

Option 3: f-string

This is the most efficient option if you are using Python 3.6 or greater.

How to use it?

Example 3.1: Simple syntax

>>> name =  "Naveen"
>>> lastname = "Kumar"
>>> f"My name is {name}{lastname}"
'My name is Naveen Kumar'

Example 3.2: Any expression

>>> f"{5*2}"
'10'

Example 3.3: Any function

def lowercase(x):
	return x.lower()

greetings = 'HELLO'

>>> f"{lowercase(greetings)}"
'hello'

>>> f"{greetings.lower()}"
'hello'

Example 3.4: Dictionary

>>> info = {'name': 'Naveen', 'lastname': 'Kumar', 'age': 20}
>>> f"My firstname is {info['name']}. My lastname is {info['lastname']}. My age is {info['age']}."
'My firstname is Naveen. My lastname is Kumar. My age is 20.'

Example 3.5: Multiline

>>> name = "Naveen"
>>> lastname = "Kumar"
>>> age = 20
>>> 
>>> info = (
... f"My first name is {name}. "
... f"My last name is {lastname}. "
... f"My age is {age}."
... )
>>> info
'My first name is Naveen. My last name is Kumar. My age is 20.'

You have to put ‘f’ in front of every line.

Example 3.5: Floating value with 2 decimal points

>>> num = 23.3
>>> 
>>> print(f"{x:.2f}")
>>> 23.30

SUMMARY

For Python version >=3.6, use f-string

f'My name is {name}'