DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Python F-Strings
  • Using Regular Expressions in Python: A Brief Guide
  • JSON-Based Serialized LOB Pattern
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • AI in SRE: What's Actually Coming in 2026
  • How to Detect Spam Content in Documents Using C#
  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Building Production-Grade GenAI on GCP with Vertex AI Agent Builder
  1. DZone
  2. Coding
  3. Languages
  4. Efficient String Formatting With Python f-Strings

Efficient String Formatting With Python f-Strings

f-string simplifies string formatting, which provides a concise and readable way to embed expressions inside string literals.

By 
Sameer Shukla user avatar
Sameer Shukla
DZone Core CORE ·
Jan. 02, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

f-strings are a feature introduced in Python 3.6 to simplify string formatting. It provides a concise and readable way to embed expressions inside string literals, making string formatting more intuitive and efficient.

Basic Syntax

f-strings are created by prefixing a string literal with the letter 'f.' Inside the string, expressions enclosed in curly braces {} are evaluated and replaced with their values at runtime.

Python
 
name = "John Doe"
age = 35 

message = f"Hello, my name is {name} and I am {age} years old."
print(message)


Expression Inside f-strings

f-strings supports the inclusion of dynamic values by placing the expression within curly braces {} as mentioned earlier. These expressions are evaluated at runtime, allowing for the inclusion of variables, calculations, functions, ternary operations, and other dynamic content. 

Python
 
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}"
print(result) # 30


Variable Access

Variables in the current scope can be accessed directly within the f-string. This provides a concise way to reference and display variable values. 

Python
 
name = "John Doe"
age = 35 

message = f"Hello, my name is {name} and I am {age} years old."
print(message) # Hello, my name is John Doe and I am 35 years old.


Function Calls

We can call functions and methods inside f-strings, and their return values will be included in the resulting string. 

Python
 
name = "John Doe"
age = 35

def greet(name):
    return f"Hello {name} here"

message = f"{greet(name)} and I am {age} years old."
print(message) # Hello John Doe here and I am 35 years old.


Another example would be to use an existing function inside f-string, for example, finding the max number from a list of numbers.

Python
 
numbers = [1,2,3,4,5]
result = f"The largest number is {max(numbers)}."
print(result)  # Output: The largest number is 5.


Formatting Options

f-strings support various formatting options, similar to the format () method. You can specify the format using the ":" character inside the curly braces.

Python
 
pi = 3.141592653589793

formatted_pi = f"Value of pi: {pi:.2f}"
print(formatted_pi) # 3.14


In the example above, .2f specifies that the floating-point number should be formatted with two decimal places.

Conditional Expressions (Ternary Operator)

We can use the ternary operator inside the f-strings for evaluating conditional expressions. 

Python
 
def result(score):
    return f"The student {'passed' if score >=70 else 'failed'}"

result(85) # 'The student passed'
result(60) # 'The student failed'


Additional Key Points

  • List Comprehensions: We can use list comprehensions inside f-strings to create or display lists. 
Python
 
numbers = [1,2,3,4,5]
result = f"The Squares of numbers inside the list are {[n * 2 for n in numbers]}"
# 'The Squares of numbers inside the list are [2, 4, 6, 8, 10]'


  • Attribute Access: Attributes of objects can be accessed directly with-in f-strings.
Python
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("John Doe", 35)
description = f"{person.name} is {person.age} years old."


  • Dictionary Access: f-strings allow accessing values from the dictionary using keys.
Python
 
student_grades = {"John": 90, "Bob": 80, "Charlie": 95}
message = f"John scored {student_grades['John']} in the exam." 


  • Date and Time Formatting: When working with date and time objects, expressions inside f-strings can format and display them.
Python
 
from datetime import datetime
now = datetime.now()
formatted_date = f"Current date and time: {now:%Y-%m-%d %H:%M:%S}."


  • Multiline Strings: f-strings allow us to create multi-line strings easily by enclosing expressions in triple quotes (''' or """). Here's an example of using a multi-line f-string:
Python
 
name = "John Doe"
age = 35
occupation = "Software Engineer"

# Multi-line f-string
message = f"""
Hello, my name is {name}.
I am {age} years old.
I work as a {occupation}.
"""

print(message)


Advantages of Using f-strings Over Other String Formatting Options in Python

  • Performance: Benchmarks often show f-strings to be slightly faster than other formatting methods.  
Python
 
import timeit

import timeit

def fstring_formatting():
    name = "John"
    age = 35
    message = f"Hello, {name}! You are {age} years old."

def format_method():
    name = "John"
    age = 35
    message = "Hello, {}! You are {} years old.".format(name, age)

def percent_operator():
    name = "John"
    age = 35
    message = "Hello, %s! You are %d years old." % (name, age)

fstring_time = timeit.timeit(fstring_formatting, number=9000000)
format_time = timeit.timeit(format_method, number=9000000)
percent_time = timeit.timeit(percent_operator, number=9000000)

print("F-string time:", fstring_time) # 1.5446170830000483
print("Format method time:", format_time) # 2.038085499999852
print("Percent operator time:", percent_time) # 2.0135472500001015


  • Readability: f-strings allow variables, expressions, and function calls to be directly embedded within the string, making for cleaner and more intuitive code. It also eliminates the need for multiple string concatenations and improves readability.
  • Clearer formatting: The intent of the string formatting is more evident within the string itself, making code easier to understand and maintain.
Attribute (computing) Dictionary (software) Object (computer science) Python (language) Strings Syntax (programming languages)

Opinions expressed by DZone contributors are their own.

Related

  • Python F-Strings
  • Using Regular Expressions in Python: A Brief Guide
  • JSON-Based Serialized LOB Pattern
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook