f-strings in Python

Python f-strings or formatted strings are new way of formatting strings introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation. They provide a better way to format strings and make debugging easier too.

What are f-strings?

Strings in Python are usually enclosed in “ ” (double quotes) or ‘ ‘ ( single quotes). To create f-Strings, you only need to add an f or an F before the opening quotes of your string. For example,

“Anna” is a string whereas f”Anna” is an f-String.

f-Strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

Why do we need f-Strings?

Before Python 2.6, to format a string, one would either use % operator or string.Template module. Later str.format method came along and added to the language a more flexible and robust way of formatting a string.

%formatting: great for simple formatting but limited support for strings, ints, doubles etc., We can’t use it with objects.

msg = ‘hello world’

‘msg: %s’ % msg

Output:
'msg: hello world'
Template strings:

Template strings are useful for keyword arguments like dictionaries. We cannot call any function and arguments must be string.

msg = ‘hello world’

‘msg: {}’.format(msg)

Output:
'msg: hello world'
String format():

String format() function was introduced to overcome the limitations of %formatting and template strings. But this also has verbosity.

age = 3 * 10

‘My age is {age}.’.format(age=age)

Output:
'My age is 30.'

Introduction of f-string in Python is to have minimal syntax for string formatting.

f-String Syntax:
f"This is an f-string {var_name} and {var_name}."

Enclosing of variables are within  curly braces {}

Example:

val1 = ‘Abaython’

val2 = ‘Python’

print(f”{val1} is a portal for {val2}.”)

Output:
Abaython is a portal for Python.

How to evaluate expressions in f-String?

We can evaluate valid expressions on the fly using,

num1 = 25

num2 = 45

print(f”The product of {num1} and {num2} is {num1 * num2}.”)

Output:
The product of 25 and 45 is 1125.
How to call functions using f-String?

def mul(x, y):

    return x * y

print(f’Product(10,20) = {mul(10, 20)}’)

Output:
Product(10,20) = 200