Introduced in Python 3.6, f-strings (formatted string literals) are currently the most recommended way to embed variables and calculations into strings.
Compared to the traditional .format() method or the % operator, f-strings reduce the amount of code required and significantly improve readability. They also have the advantage of faster execution speed.
This article explains everything from the basic usage of f-strings to advanced features like expression evaluation and formatting.
Basic Syntax of f-strings
To use an f-string, add f or F immediately before the string’s starting quote (" or '). Then, write variable names or expressions inside {} (curly braces) within the string.
Syntax:
f"String {variable_name} String"
Specific Usage Example: Inventory Management System
Here is an example program that displays a product name and its stock count.
product_name = "Gaming Monitor"
current_stock = 15
# Embed variables using an f-string
status_message = f"Product Name: {product_name} | Stock: {current_stock}"
print(status_message)
Execution Result:
Product Name: Gaming Monitor | Stock: 15
You can see that the variables are automatically converted to strings and embedded in the specified positions.
Expression Evaluation and Method Calls inside {}
A powerful feature of f-strings is that you can write Python expressions (calculations) and method calls directly inside the {} brackets, rather than just simple variables.
Embedding Calculations
You can calculate the total inventory value from the unit price and stock count and display it on the spot.
unit_price = 25000
stock = 4
# Perform multiplication inside {}
total_value_msg = f"Total Value: {unit_price * stock} yen"
print(total_value_msg)
Execution Result:
Total Value: 100000 yen
Method Calls
It is also possible to display the result of a method execution, such as a string method.
code = "item-a001"
# Call the .upper() method to convert to uppercase
formatted_code = f"Product Code: {code.upper()}"
print(formatted_code)
Execution Result:
Product Code: ITEM-A001
Formatting
In f-strings, you can control number separators and decimal places by writing a format specifier after a colon in the format {value:format}.
price = 12800
tax_rate = 0.1
# 1. Comma separator (:,)
# 2. Display up to 1 decimal place (:.1f)
price_info = f"Price: {price:,} yen (Inc. Tax: {price * (1 + tax_rate):,.1f} yen)"
print(price_info)
Execution Result:
Price: 12,800 yen (Inc. Tax: 14,080.0 yen)
Summary
- Add
fbefore the quote (e.g.,f"...") to create an f-string. - Embed variable values using
{variable_name}. - Embed calculation results or method return values using
{expression}. - Specify display formats (digit separators, decimal places) using
{value:format}.
If you are using Python 3.6 or later, it is recommended to prioritize f-strings over .format() for better readability and performance.
