Udit Vashisht
Author: Udit Vashisht


Python F String - The Ultimate Usage Guide

  • Aug. 20, 2019, 12:06 p.m.
  • 8 minutes read
  • 7850 Views
Python F String - The Ultimate Usage Guide

Python F String

Python’s F-String was added in Python 3.6.0 as PEP-498 – Literal String Interpolation. Before the introduction of Python f-string, there were other methods of formatting like %-formatting, str.format() or string.Template(). These methods have their advantages, but the major disadvantage is that they are difficult to use. But, Python f-string is termed as the easiest way to format the string and hence became the most popular feature of Python3.

%-formatting

Before the f-string 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 that it faces is that it encounters an error if more than one value is provided. This is well documented in the official documentation of Python f-string.

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

# If the msg 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 simple method to overcome this:-

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

But, str.format() is simple 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-string

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

How to use f-string in Python?

To use Python f-string, the 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-string

You can directly do the calculations inside an 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 10.'
>>>

Python f-string - The Escape Sequences

If you have done formatting in Python, you know that the escape character comes handy. However, f-string do not support the escape character inside the expression portion. It means that the f-string’s expression part can not include 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 (the 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-string - 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-string

If you want to print braces using the Python F-string. 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-string - Working with dictionaries

Since dictionaries involve quotes, using them inside the f-string could be 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 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-string- Specifying formats

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

For example, we can have a number with 0 padding using f-string 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 also format the dates using datetime module in Python f-string 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-string 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-string in Python

We can also f-string in multiline string 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.'
>>>

You can also, do the same using “”” (triple quotes) as under. But this will add new line (/n) at every press of return/enter:

>>> name = "Saral"
>>> age = 30
>>> profession = "Pythonista"
>>> sentence = f""" My name is {name}.
... I am {age} years old.
... I am a {profession}.
... """
>>> sentence
' My name is Saral.\nI am 30 years old.\nI am a Pythonista.\n'
>>> 

String Formatting in Python at Glance

# Method Expression
1 %-formatting 'text %s' % variable
2 str.format() 'text {}.'.format(variable)
3 f-string f'text {variable} text .....'

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

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.



Related Posts

Set Passwords and Secret Keys in Environment Variables (Mac/Linux/Windows) - Python Quicktip
By Udit Vashisht | 1 month, 3 weeks ago

Hide Passwords and Secret Keys in Environment Variables

If you are into python , there is a fair chance that you would have contributed to open-source or had your code snippets/projects on Github or BitBucket.Some time your code involves some important credentials like passwords or secret keys ...

Read More
Python 3 useful tip-strip()-A useful built-in type.
By Udit Vashisht | 9 months, 1 week ago

Have you ever stumbled across a set of data that contains an extra underscore, character, or word as prefix or suffix, which you want to get rid of?

Python is known for having a resourceful standard library with lots of built-in types that can do a set of tasks in ...

Read More
Difference between "==" and "is" in Python- Quick Tip
By Udit Vashisht | 2 months ago

What is the difference between “==” and “is” variable in Python?

If you are new to python you must have seen programmers using “==” and “is”, sometimes even interchangeably. Prima-facie, they look similar and many times you will use any of them. But there is a big difference between them. ...

Read More
Search