tech beamers
  • Python Lab
    • Python Online Compiler
    • Python Code Checker
    • Python Coding Exercises
    • Python Coding Quizzes
  • SQL Practice
  • SQL Prep
  • Selenium Practice
  • Software Testing
tech beamers
Search
  • Python Lab
    • Python Online Compiler
    • Python Code Checker
    • Python Coding Exercises
    • Python Coding Quizzes
  • SQL Practice
  • SQL Prep
  • Selenium Practice
  • Software Testing
Follow US
© TechBeamers. All Rights Reserved.
Python Tutorials

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

Last updated: Nov 30, 2025 10:52 am
Meenakshi Agarwal
By Meenakshi Agarwal
No Comments
1 day ago
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?
    • F-String Syntax
    • F-String Basic Example
  • Simple Ways to Use F-strings
    • Using F-strings in Conversions
    • Generate Raw String from F-string
    • Using F-string with Classes
    • Using F-string in a Function
    • Use Whitespaces in F-strings
    • F-string with Python Lambda
    • Braces within an F-string
    • Backslashes within F-string
  • Ready to Use Python F-Strings Efficiently?
Simple ways to use f-strings in Python programs.

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.

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.

F-String Syntax

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.

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.

F-String Basic Example

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.

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

Simple Ways to Use F-strings

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.

Using F-string in a 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

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

F-string with Python Lambda

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.

Ready to Use Python F-Strings Efficiently?

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.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy Coding,
TechBeamers

Related

Share This Article
Whatsapp Whatsapp LinkedIn Reddit Copy Link
Meenakshi Agarwal Avatar
ByMeenakshi Agarwal
Follow:
I’m Meenakshi Agarwal, founder of TechBeamers.com and ex-Tech Lead at Aricent (10+ years). I built the Python online compiler, code checker, Selenium labs, SQL quizzes, and tutorials to help students and working professionals.
Previous Article python read file line by line techniques 3 Ways to Read a File Line by Line in Python (With Examples)
Next Article Python String Find with Examples Python String Find()
Leave a Comment

Leave a Reply

Most Popular This Month

  • → Python Online Compiler
  • → Python Code Checker
  • → Free Python Tutorial
  • → SQL Practice Queries
  • → Code to Flowchart Tool
  • → Python Syntax Guide
  • → Python List & Dict Questions
  • → Selenium Practice Test Page

RELATED TUTORIALS

Python List Remove Method Explained with Examples

List Remove Method

By Meenakshi Agarwal
1 day ago
Convert Python String to Int & Int to String with Examples

Python String to Int and Back to String

By Meenakshi Agarwal
1 day ago
Python Numbers, Type Conversion, and Mathematics

Python Numbers Guide

By Meenakshi Agarwal
1 day ago
Python List Clear Method Explained with Examples

List Clear Method

By Meenakshi Agarwal
1 day ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use