DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Python f-strings - The Ultimate Usage Guide

  • 12 minutes read
  • 76641 Views
Python f-strings - The Ultimate Usage Guide

    Table of Contents

Python f-strings

Python f-string is a string literal that starts with letter f and has curly braces ({}, placeholder) containing the variables, which will change into the value of that variable. It was added in Python 3.6.0 as PEP-498 – Literal String Interpolation. Before the introduction of f-string, there were other methods of string formatting like %-formatting, str.format() or string.Template(). These string formatting methods have their advantages, but the major disadvantage is that they are difficult to use. But, f-string is termed as the easiest way to format the string and hence became the most popular feature of Python 3. Python f-strings overcome most of the issues. Therefore, the current version of Python (Python 3.6 and above) comes with f-string. It uses minimal syntax and is more convenient and readable than any of the other string formatting method in Python.

Python string formatting at a glance

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

%-formatting in Python

Before f-strings, %-formatting was used for string formatting in Python, which can only format integers, strings, and doubles. Any other type will either not be supported or converted into one of these formats. If more than one value is provided, %-formatting encounters a TypeError. This is well documented in the official documentation of Python f-strings.

>>> 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() in Python

The str.format() method addresses many issues of %-formatting as in supporting multiple parameters which could be further extended by using __format()__. The major issue with it is - verbosity. Have a look at the following code, the variable ‘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 following shorthand 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.

How to use f-strings in Python?

To use f-strings, 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-Placeholder) and ‘ (closing single quote). The syntax for it is as under:-

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

You can simply print using f-string in Python by typing print(f ‘ {variable} .....’). The following example demonstrate the simple usage:

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.

How to use methods, functions, lambda functions and calculations in Python f-string?

You can directly do the calculations inside Python f-strings and can even use methods and functions by adding them inside the curly braces {}.

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.'
>>>

Lambda functions

>>>print(f'4 into 4 is {(lambda x: x*4)(4)}.')
'4 into 4 is 16.'
>>>

How to use escape character in Python f-strings?

Python f-strings do not support the escape character inside the expression portion. It means that the f-string’s expression part can not include a backslash or the escape character. Instead of using the escape character you will have to use different quotes inside the expression. However, the escape character (backslash) is allowed in the string portion of the text.

>>> 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
>>> 
>>> f'Text in {"double-quotes"}.'
'Text in double-quotes.'
>>> 
f'String portion\'s backslash are allowed, {"hurray"}.'
"String portion's backslash are allowed, hurray."

Inline comments in Python f-string

You can not use inline comments inside the expression portion of the Python f-strings.

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

How to print braces/brackets using Python f-strings?

You can print braces/brackets using the Python f-strings by using 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"}}'
>>> 

How to do a dictionary format with f-strings in Python 3?

Since dictionaries involve quotes, using them inside the f-string could be tricky. The best way is to use different quotes than the outside expression i.e. double-quotes, provided you are using single quotes for the f-strings expression.

>>> 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-strings padding

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

How to pad string with zero in Python f-strings (0-Padding)?

We can pad a string with zeros (0-Padding) in Python f-strings by adding {variable:0N} inside the braces, where N stands for total number of digits-

>>> 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
>>> 

How to add decimal places in a float in Python f-strings (Formatting a float)?

We can define the fixed number of digits after decimal in a float using fstrings by adding {variable:.Nf}, where N stands for total number of decimal places. 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
>>> 

How to format dates in Python f-strings?

We can also format the dates in Python f-string by using datetime module and adding the desired format in curly braces {date:directive}.You can find more directives (i.e. %A, etc.) from official page of datetime module.:-

>>> 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.'

How to add space padding in Python f-strings?

You can add spaces (padding) to a string in Python f strings by adding {variable:N} where N is total length. If the variable is 1 and N is 4, it will add three spaces before 1, hence making the total length 4.

>>> for n in range(1,11):
...     print(f'The number is {n:4}')
... 
The number is    1
The number is    2
The number is    3
The number is    4
The number is    5
The number is    6
The number is    7
The number is    8
The number is    9
The number is   10
>>> 

How to justify a string in Python f-strings?

We can justify a string in Python f-strings using {variable:>N} where N is the total length.

s1 = 'Python'
s2 = 'ython'
s3 = 'thon'
s4 = 'hon'
s5 = 'on'
s6 = 'n'

print(f'{s1:>6}')
print(f'{s2:>6}')
print(f'{s3:>6}')
print(f'{s4:>6}')
print(f'{s5:>6}')
print(f'{s6:>6}')
...
Python
 ython
  thon
   hon
    on
     n

....

Python f-strings padding at glance

# Padding Expression
1 0 Padding {variable:0N}
2 Decimal Places {variable:.Nf}
3 Date Formatting {date : Directive}
4 Space Padding {variable:N}
5 Justified string {variable:>N}

How to print various numeric notations in Python f-strings?

The various numeric notations like hexadecimal, octal, scientific, etc. can be printed in Python f-strings using ‘{variable:notation}’ as shown in the example below:-

number = 800

# Hexadecimal
print(f'{number:x}')

# Ocatal
print(f'{number:o}')

# Scientific
print(f'{number:e}')

...
320
1440
8.000000e+02

How to print raw f-strings in Python?

We can also print raw f-strings by using {variable!r}

>>> 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 f-strings in multiline string by adding f in front of every line as shown under.

>>> 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'
>>> 

Is Python f-strings faster?

Yes, Python f-strings are faster than any other string formatting in Python i.e. str.format and %-formatting. The following examples show that the f-strings are twice faster than str.format() and atleast 80% faster than %-formatting.

>>>import timeit 
>>>timeit.timeit("""name="Saral"
... age = 30
... '%s is %s.' %(name, age)""", number = 100000)
0.04012815800000169
>>> timeit.timeit("""name="Saral"
... age = 30
... '{} is {}.'.format(name, age)""", number = 100000)
0.05490115599999967
>>> timeit.timeit("""name="Saral"
... age = 30
... f'{name} is {age}.'""", number =100000)
0.025380449000010685

Conclusion - What are the advantages of Python f-strings?

From above, we can conclude that the main advantages of using Python f-strings are:-

  • It is the fastest string formatting method in Python.
  • It is more readable.
  • It is concise.
  • It is less prone to error.
  • It is less verbose.

Hence, if you were wondering which string formatting method in you should use. I hope that you have found your answer that you must use Python f-strings for string formatting. So, just dive into it and start using Python f-strings.

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

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
Difference between "==" and "is" in Python- Quick Tip
By Udit Vashisht

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
Python Logging Module - A Primer
By Udit Vashisht

Logging in python

Logging is the module in the standard library of python. Logging is an important tool for a programmer or developer, as it gives more insights about the code and any errors in it. In this tutorial, we will learn all about the python logging module. ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python