PYTHON

Python f-String: Syntax, Usage, and Examples

A formatted string, or f-string in Python, offers a modern and efficient way of string formatting. Introduced in Python 3.6, f-strings use curly braces ({ and }) to embed Python expressions inside string literals.

How to Use f-Strings in Python

f-strings use a straightforward syntax. To create an f-string, prefix a string literal with f and include any Python expression inside curly braces ({ and }):

name = "Joanna"
age = 42
greeting = f"Hello, {name}. You are {age} years old."

f-strings can incorporate advanced string methods, enabling dynamic transformations or concatenations directly within the expression. For example:

text = "hello"
formatted = f"{text.upper()} WORLD"
print(formatted)  # Outputs: HELLO WORLD

When to Use f-Strings

In Python, string formatting with f-strings is useful in various scenarios, such as handling data types like strings, numbers, or dates. They are particularly beneficial for creating readable and concise code. This includes:

  • Formatting numbers with specified decimal places.
  • Embedding calculations or conditions.
  • Using formatted string literals for complex data outputs.

Examples of f-Strings in Python

Dynamic Content Creation

f-strings are ideal for building more complex string expressions, such as user notifications or personalized messages. As an example, consider a user performing an action on a website. If successful, the username and the action might display in a message.

username = "fsociety"
action = "uploaded a video"
message = f"Thank you, {username}. You have successfully {action}."

Complex Calculations Display

f-strings help make complex calculations in applications more user-friendly. For instance, in a finance application, they can clearly show compounded interest over time. This makes it easier to understand the calculations.

principal_amount = 1000
interest_rate = 0.05
years = 5
final_amount = principal_amount * (1 + interest_rate) ** years
print(f"After {years} years, your investment will be worth ${final_amount:.2f}.")

Iterating Over Data

f-strings simplify displaying data while working with an iterator or iterable objects like lists and dictionaries.

products = ["VR goggles", "Headphones", "Watch"]
for i, product in enumerate(products, start=1):
    print(f"Product {i}: {product}")

f-strings also work seamlessly with tuple values, allowing you to extract and display their elements directly:

coords = (10, 20)
print(f"Coordinates: x={coords[0]}, y={coords[1]}")
# Outputs: Coordinates: x=10, y=20

Conditional Outputs in Messages

In addition, f-strings allow for conditional logic, making it easy to tailor messages based on specific conditions or variables.

order_total = 150
free_shipping_threshold = 100
shipping_status = "eligible" if order_total >= free_shipping_threshold else "not eligible"
print(f"Your order is {shipping_status} for free shipping.")

Formatting Date and Time for User Interfaces

With f-strings, you can make sure dates and times are easy to read. You can adjust datetime objects to match local formats or include replacement fields.

from datetime import datetime
user_last_login = datetime(2024, 2, 16, 11, 38)
print(f"Last login: {user_last_login:%B %d, %Y at %H:%M}")

JSON Representation

f-strings also support JSON-friendly representations using repr, which ensures that objects are formatted in a readable string form.

import json
data = {"name": "Alice", "age": 30}
print(f"User data: {json.dumps(data)}")

Learn More About String Formatting in Python

Complex Expressions and Function Calls

f-strings can include more than variables and values. They can include expressions, function calls, and even conditional logic:

def double(x):
    return x * 2

value = 10
print(f"Double {value} is {double(value)}")

Format Specification Mini-Language

Python's so-called format mini-language provides advanced control over string formatting. Instead of just inserting values, the format mini-language allows you to specify field width, alignment, precision, and more. However, the formatting syntax must follow a specific order, with each modifier category having specific symbols.

The format mini-language supports a wide range of options for creating string representations of values. Numbers and dates are the most common values to format:

  • You can control the precision of floating-point numbers, display format, or the grouping of thousands with number formatting. For instance, you can use a comma as a thousands separator:

    number = 1234567.89
    print(f"Formatted Number: {number:,.2f}")  # Includes thousands separator
    
  • The mini-language also supports other numeral systems, such as octal, which can be used in specific programming contexts:

number = 255
print(f"Octal representation: {number:o}")  # Outputs: Octal representation: 377
  • When formatting numbers, you can also use zeros for padding, ensuring fixed-width alignment in numerical outputs:

num = 42
print(f"Zero-padded number: {num:03}")  # Outputs: Zero-padded number: 042
  • In addition, the mini-language allows the representation of a decimal integer, which is especially helpful for clear numeric displays:

number = 42
print(f"Decimal integer: {number:d}")  # Outputs: Decimal integer: 42
  • You can also customize the formatting of dates and times:

    from datetime import datetime
    current_date = datetime.now()
    print(f"Current date: {current_date:%Y-%m-%d}")
    

Refer to the official Python documentation if you want to learn about additional capabilities of the format mini-language.

Alternative String Formatting Methods

Python f-string only became popular with Python 3.6. Before f-strings, formatting strings required the % operator, the str.format() method, or template strings.

  • The % operator is Python's original method for string formatting, inspired by the printf syntax of the C programming language. The % operator method uses format specifiers like %s for strings and %d for integers to insert values into a string template.

    name = "Joanna"
    age = 42
    print("My name is %s and I am %d years old." % (name, age))
    
  • Introduced in Python 2.6, the str.format() method is more flexible than the % operator. The string module's formatting function supports both positional and keyword arguments, with placeholders surrounded by curly braces ({ and }).

    name = "Joanna"
    age = 42
    print("My name is {0} and I am {1} years old.".format(name, age))
    

    print("My name is {name} and I am {age} years old.".format(name="Joanna", age=42))
    
  • Python's string Template class provides another way to format strings using a simpler syntax. While less powerful, it can be useful for straightforward substitutions. An example might be handling user-generated format strings (to avoid security issues).

    from string import Template  # Imports the template class
    
    template = Template("My name is $name and I am $age years old.")
    print(template.substitute(name=name, age=age))
    

f-strings became the most popular string formatting method in Python because of their speed and straightforward syntax. However, knowing the other string formatting methods is still important when working with older Python code.

Learn Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH