Three Ways to Format Strings in Python: f-strings, .format(), and % Operator

Discover the pros and cons of each method and learn when to use them in your Python projects

Max N
2 min readApr 5, 2024

Formatted strings play a vital role in displaying output and logging messages in Python applications. Python offers three ways to format strings: f-strings, .format(), and % operator. Each has its unique syntax, strengths, and weaknesses.

This tutorial will compare and contrast these methods, helping you choose the right one for your needs.

F-Strings

Introduced in Python 3.6, formatted string literals (f-strings) offer a concise way to embed expressions within strings using curly braces ({}) notation. F-strings support various data types, operators, and functions, allowing flexible and readable code.

Example:

first_name = "Alice"
last_name = "Smith"
full_name = f"{first_name} {last_name}"
print(full_name) # Output: Alice Smith

quantity = 5
item_cost = 10.99
total_cost = f"Total cost: ${quantity * item_cost:.2f}"
print(total_cost) # Output: Total cost: $54.95

Pros:

  • Readability: Embedding variables directly within strings improves clarity.

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.