TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python F-Strings: What They Are and How to Use
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python F-Strings: What They Are and How to Use

Last updated: Oct 30, 2023 11:39 am
By Meenakshi Agarwal
Share
9 Min Read
Python f-string for string formatting
Python f-string for string formatting
SHARE

This tutorial covers the concept of Python f-strings and explains string formatting in detail with self-explanatory examples. It is an implementation of the PEP 498 specifications for formatting Python strings in an entirely new way. It is available in Python version 3.6 and above.

Contents
What are f-strings in Python?Python f-string syntaxF-strings examplesUsing f-strings in conversionsGenerate raw string from f-stringUsing f-string with classesPython F-string with a user-defined functionWhitespaces in f-stringsPython f-string with Anonymous functionBraces within an f-stringBackslashes within f-string

Python f-string uses a new convention that requires every string should begin with the ‘f’ prefix. And hence, it derives its name from this synthesis. One of the main advantages that it brings is making the string interpolation easier. Also, it insists on having a simple way to use Python expressions within a string literal for formatting.

Python F-Strings: A Powerful Tool for String Formatting

Once you get used to using f-strings, you will find it the easiest and the best way to handle strings. Let’s unwrap every little detail about f-string step by step and with examples.

By the way, there are several methods of formatting a string in Python. Some of them are by using the % operator and the format() function. If interested, please read about them as well.

What are f-strings in Python?

F-strings are a new method for handling strings in Python. It is based on the PEP 498 design specs. To create an f-string, you need to prefix it with the ‘f’ literal. Its primary purpose is to simplify the string substitution.

It pushes for a minimal syntax and evaluates expressions at run-time. This feature is not available in any version below Python 3.6. Hence, use it or a higher version of Python.

Python f-string syntax

You can use the below statement to create an f-string in Python.

f'Python {expr}'

The expr can be anything from a constant, an expression, a string or number, a Python object, etc.

Here’s a simple example to illustrate its usage.

version = 3.6
feature = 'f-string'

str_final = f'Python {feature} was introduced in version {version}.'
print(str_final)

After executing the code, you get to see this result:

Python f-string was introduced in version 3.6.

F-strings examples

In this section, we’ve brought up several elementary cases of f-strings. Check below:

title = 'Joshua'
experience = 24

dyn_str = f'My title is {title} and my exp is {experience}'
print(dyn_str)

# We can use f or F interchangeably
print(F'My title is {title} and my exp is {experience}')

title = 'Sophia'
experience = 14

# dyn_str doesn't get re-evaluated, if the expr changes later.
print(dyn_str)

Python is an interpreted language and runs instructions one by one. If the f-string expression is evaluated, then it won’t change whether the expression changes or not. Hence, in the above example, the dyn_str value is intact even after the title and experience variables have different values.

Using f-strings in conversions

The f-strings allow conversion like converting a Python date-time to other formats. Here are some examples:

from datetime import datetime

# Initializing variables
title = 'Abraham'
experience = 22
cur_date = datetime.now()

# Some simple tests
print(f'Exp after 10 years will be {experience + 10}.') # experience = 32
print(f'Title in quotes = {title!r}') # title = 'Abraham'
print(f'Current Formatted Date = {cur_date}')
print(f'User Formatted Date = {cur_date:%m-%d-%Y}')

After code execution, the outcome is:

Exp after 10 years will be 32.
Title in quotes = 'Abraham'
Current Formatted Date = 2019-07-14 07:06:43.465642
User Formatted Date = 07-14-2019

Generate raw string from f-string

F-strings can also produce raw string values.

To print or form a raw string, we need to prefix it using the ‘fr’ literal.

from datetime import datetime

print(f'Date as F-string:\n{datetime.now()}')
print(fr'Date as raw string:\n{datetime.now()}')

It tells us the difference between f vs. r strings. The output is:

Date as F-string:
2019-07-14 07:15:33.849455
Date as raw string:\n2019-07-14 07:15:33.849483

Using f-string with classes

Apart from using f-string to format Python strings, we can use them to format class objects and their attributes.

Here is a sample Python class using f-string for formatting its members:

class Student:
    age = 0
    className = ''

    def __init__(self, age, name):
        self.age = age
        self.className = name

    def __str__(self):
        return f'[age={self.age}, class name={self.className}]'


std = Student(8, 'Third')
print(std)

print(f'Student: {std}\nHis/her age is {std.age} yrs and the class name is {std.className}.')

After running the above code, you get to see this outcome:

[age=8, class name=Third]
Student: [age=8, class name=Third]
His/her age is 8 yrs and the class name is Third.

Python F-string with a user-defined function

Let’s create one of our custom functions and see how can it be called from the f-string

def divide(m, n):
    return m // n

m = 25
n = 5
print(f'Divide {m} by {n} = {divide(m, n)}')

The above snippet outputs the following:

Divide 25 by 5 = 5

Whitespaces in f-strings

Python dismisses any whitespace character that appears before or after the expression in an f-string. However, if there is some in the overall sentence, then it is eligible to be displayed.

kgs = 10
grams = 10 * 1000

print(f'{ kgs } kg(s) equals to { grams } grams.')

When you run the sample, you get to see this output:

10 kg(s) equals to 10000 grams.

Python f-string with Anonymous function

Anonymous function, also known as Python lambda expression, can work alongside f-strings. However, you need to be cautious when using “!” or “:” or “}” symbols. If they aren’t inside parentheses, then it represents the end of an expression.

Also, lambda expr uses a colon which can cause adverse behavior. See below.

lambda_test = f"{lambda x: x * 25 (5)}"

The above statement would cause the following error:

  File "", line 1
    (lambda x)
             ^
SyntaxError: unexpected EOF while parsing

To use a colon safely with Lambda, wrap it inside parentheses. Let’s check out how:

lambda_test = f"{(lambda x: x * 25) (5)}"
print(lambda_test)

After running the updated code, you see the following:

125

If you are interested, then also read different usages of Lambda in Python.

Braces within an f-string

If you like to see a pair of “{}” in your string, then have double braces to enclose:

lambda_test = f"{{999}}"
print(lambda_test)

Output:

{999}

If you try with triple braces, then also, it will only show one set of braces.

lambda_test = f"{{{999}}}"
print(lambda_test)

Output:

{999}

Backslashes within f-string

We use backslash escapes in a part of a Python f-string. But, we can’t use them to escape inside the expression.

lambda_test = f"{"Machine Learning"}"
print(lambda_test)

The above code produces the following error:

  File "jdoodle.py", line 2
    lambda_test = f"{"Machine Learning"}"
                            ^
SyntaxError: invalid syntax

We can fix this by placing the result of the expression and using it directly in the f-string:

topic = "Machine Learning"
lambda_test = f"{topic}"
print(lambda_test)

The result is:

Machine Learning

Also, note that you should not insert comments (using a “#” character ) inside f-string expressions. It is because Python would treat this as a syntax error.

We hope that after wrapping up this tutorial, you should feel comfortable using the Python f-string. However, you may practice more with examples to gain confidence.

Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article MySQL Aggregate Functions with Examples MySQL Aggregate Functions
Next Article MySQL Insert to Add Single Multiple Rows MySQL Insert Statement to Add Rows

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x