Python 3's f-Strings: Usage Guide

Python 3's f-Strings: Usage Guide

Python 3's f-Strings - A complete guide to the most well received feature of Python 3

Python F String

Python’s F String was launched with Python 3.6.0 by PEP-498 – Literal String Interpolation and was called python f strings in layman’s language.Before the introduction of Python f strings, there were other methods of formatting like %-formatting , str.format() or string.Template(). All these methods have their advantages and disadvantages but were very difficult to use. But Python f strings have become the most popular feature of Python.

%-formatting

Before the advent of f-strings in Python, %-formatting was used, which can only format integers, strings and doubles. Any other type will either not be supported or converted into one of these. One of the major issues which it faces is that it encounters an error if more than one value is provided. This is well documented in official documentation of Python f string

>>> msg = 'disk failure'
>>> 'error: %s' % msg
'error: disk failure'

If message is a tuple

>>> msg = ('disk failure', 32) >>> 'error: %s' % msg Traceback (most recent call last):  File "<stdin>", line 1, in <module> TypeError: not all arguments converted during string formatting

To be defensive, you can pass more than one value like this

>>> 'error: %s' % (msg,) "error: ('disk failure', 32)"

str.format()

This method addresses many issues of %-formatting as in supporting multiple parameters which could be further extended using format(). The major issue with it is verbosity. Have a look at the following code, the ‘name’ is used for so many times.:-

>>> name = "Saral"
>>> 'My name is {name}.'.format(name = name)
'My name is Saral.'
>>>

However, you can use the simpler method to overcome this:-

>>> name = "Saral"
>>> 'My name is {}.'.format(name)
'My name is Saral.'
>>>

But,this case is simpler and easy to read, only if we have fewer placeholders {} and variables. If the number of placeholders increases, we will have to go back to the placeholder and variable over and again to be correct.

Python f-strings

Python’s f strings overcome the majority of the issues discussed above. Therefore the current versions of Python (Python 3.6 and above) come with Python f-strings. It uses minimal syntax and is more convenient and readable than any of the other methods.

How to use f-strings in Python

To use Python f-strings he common practice (as detailed in the official documentation ) is to use f followed by ‘(Opening single quote) , text if any, variable in {} (single curly brackets) and ‘ (Closing single quote).

f '<text> {variable} <text> .....'

Have a look at the following example

name = "Saral"
Age = 30

print (f'My name is {name} and I am {age} years old.')

Output

My name is Saral and I am 30 years old.

Using methods, functions and calculations in Python f-strings

You can directly do the calculations inside a f-string and can even use methods and functions.

Calculations:

>>> f'8 and 10 are {8 + 10}.'
'8 and 10 are 18.'
>>> 

Methods:

name = 'saral'
>>> f'My name is {name.upper()}.'
'My name is SARAL.'
>>>

Functions:

>>> def foo():
...    return 10
>>> f'result is {foo()}.'
'result is 20.'
>>>

Python f strings - Escape Sequences

If you have done formatting in Python, you must know that escape character comes handy. However, f-strings do not support the escape character inside the expression portion.It means that f-string expression part can not inclued a backslash.

>>> f'Text in {'single quotes'}.' 
  File "<stdin>", line 1
   f'Text in {'single quotes'}.'
                    ^
SyntaxError: invalid syntax
>>> f'Text in {'single quotes'}.'
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> 

In this case, we will have to use different quotes inside the expression:-

>>> f'Text in {"double quotes"}.'
'Text in double quotes.'
>>> 

However, backslash (escape character) is allowed in the string portion of the text.

f'String portion's backslash are allowed {"hurray"}.'
"String portion's backslash are allowed hurray."

Python f stings - Inline comments

Just like backslashes, you can not use inline comments inside the expression portion of the Python F string.

>>> f'Saral is {6 * 5 #age}'
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include '#'
>>> 

Printing braces using Python F-strings

If you want to print braces using the Python F-strings. You must use two braces to print single brace and 4 braces to print double braces.

>>> f'{{"Single Braces"}}'
'{"Single Braces"}'
>>> f'{{{"This will also print Single Braces"}}}'
'{This will also print Single Braces}'
>>> f'{{{{"This will print Double Braces"}}}}'
'{{"This will print Double Braces"}}'
>>> 

Python f-stings - Working with dictionaries

Since dictionaries involve quotes, using them inside f-strings could be a bit tricky.

>>> details = {'name': 'saral', 'age' : 30}

If you use single quotes

>>> f'My name is {details['name'] and I am {details['age'].'  File "<stdin>", line 1    f'My name is {details['name'] and I am {details['age'].'                              ^ SyntaxError: invalid syntax

If you try using backslash

>>> f'My name is {details['name'] and I am {details['age'].'  File "<stdin>", line 1 SyntaxError: f-string expression part cannot include a backslash

The best way is to use different kind of quotes than outside (i.e. double quotes)

>>> f'My name is {details["name"]} and I am {details["age"]}.' 'My name is saral and I am 30.'

Python f-strings- Specifying formats

Using the f-strings in Python, we can specify the formats like zero-padding a number, digits after decimal or datetime. This is also called f-strings padding in Python.

For example, we can have an number with 0 padding using F-strings like this:-

>>> for n in range(1,11):
...     print(f'The number is {n:02}')
... 
The number is 01
The number is 02
The number is 03
The number is 04
The number is 05
The number is 06
The number is 07
The number is 08
The number is 09
The number is 10
>>> 

Similarly, we can define the number of digits after decimal in a float. This doesn’t just strip off the rest of the decimal points, but round it properly.

>>> from math import pi
>>> print(f'The value of pi is {pi:.4f}')
The value of pi is 3.1416
>>> 

We can format the dates using datetime module in Python f-strings also:

>>> import datetime
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
>>>f'The date is {date:%A, %B %d, %Y}.'
>>>'The date is Saturday, October 12, 1991.'

You can find more directives (i.e. %A etc.) from here.

Raw f-strings in Python

We can also print the raw strings as under:-

>>> name = 'Fred'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."

Multi-line f-strings in Python

We can also use multiline strings as shown below. You must note that you need to add f in front of every line otherwise you will get an error.

>>> name = 'Saral'
>>> age = 30
>>> profession = "Pythonista"
>>> sentence = (
...    f'My Name is {name}.'
...     f'I am {age} years old.'
...    f'I am a {profession}.'
... )
>>> sentence
'My Name is Saral.I am 30 years old.I am a Pythonista.'
>>>

So, just dive into it and start practicing Python f-strings.

Originally published at https://saralgyaan.com

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞  A Complete Machine Learning Project Walk-Through in Python

☞  Python Tutorial - Python GUI Programming - Python GUI Examples (Tkinter Tutorial)

☞ Python Tutorial: Image processing with Python (Using OpenCV)



Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Guide to Python Programming Language

Guide to Python Programming Language