Glossary
HTML
CSS
JavaScript
Python
Alias
Booleans
Code block
Conditions
Console
Equality operator
False
Float
For loop
Formatted strings
Functions
Greater than operator
Greater than or equal to operator
If statement
Index
Inequality operator
Integer
Less than operator
Less than or equal to operator
Lists
Parameter
Return
String
The not operator
True
Variables
While loop

append()

insert()

pop()

PYTHON

Formatted Strings in Python: Syntax, Usage, and Examples


Formatted Strings, also known as f-strings in Python, offer a modern and efficient way to format strings. Introduced in Python 3.6, f-strings use curly braces ( { and } ) to embed Python expressions inside string literals.

How to Use Formatted Strings in Python

Formatted strings use a straightforward syntax. To create a formatted 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."

When to Use Formatted Strings

In Python, string formatting with f-strings is useful in various scenarios. Examples include data output formatting, logging, and dynamic content generation. Python f-strings are particularly useful for including variables or expressions within strings.

Examples of Formatted 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

Formatted 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

Formatted strings make it easier to show data from lists or arrays in loops, improving how we present information.
products = ["VR goggles", "Headphones", "Watch"]
for i, product in enumerate(products, start=1):                  print(f"Product {i}: {product}")

Conditional Outputs in Messages

Formatted 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 formatted strings, you can make sure dates and times are easy to read. You can adjust datetime objects to match local formats.
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}")

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:
number = 1234567.89
print(f"Formatted Number: {number:,.2f}") # Includes thousands separator

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 formatting 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 to Code in Python for Free
Start learning now
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.

© 2023 Mimo GmbH