How to print formatted string in Python3?
Categories:
Mastering Formatted String Output in Python 3

Explore various techniques for creating formatted strings in Python 3, from f-strings to the format()
method and older %
operator, with practical examples and best practices.
Formatting strings is a fundamental task in programming, allowing you to create readable and dynamic output. Python 3 offers several powerful and flexible ways to achieve this, each with its own advantages. This article will guide you through the most common and recommended methods, helping you choose the best approach for your specific needs.
The Modern Approach: f-strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the most concise and readable way to format strings. They allow you to embed expressions directly inside string literals by prefixing the string with f
or F
. The expressions are evaluated at runtime and their results are inserted into the string.
name = "Alice"
age = 30
height = 1.75
# Basic f-string
print(f"Hello, my name is {name} and I am {age} years old.")
# Expressions inside f-string
print(f"Next year, I will be {age + 1} years old.")
# Formatting numbers (e.g., two decimal places)
print(f"My height is {height:.2f} meters.")
# Alignment and padding
product = "Laptop"
price = 1200.50
print(f"{'Item':<10} {'Price':>10}")
print(f"{product:<10} {price:>10.2f}")
Examples of f-string usage for various formatting needs.
The str.format()
Method
Before f-strings, the str.format()
method was the preferred way to format strings in Python 3. It provides a powerful and flexible mechanism for formatting, using curly braces {}
as placeholders for variables. You can pass arguments by position, by name, or even use object attributes and dictionary keys.
name = "Bob"
score = 95
# Positional arguments
print("{} scored {} points.".format(name, score))
# Keyword arguments
print("{player} scored {points} points.".format(player=name, points=score))
# Mixed arguments
print("The result is {0} for {player}.".format(True, player="Charlie"))
# Formatting options within placeholders
pi = 3.1415926535
print("Pi to two decimal places: {:.2f}".format(pi))
print("Binary representation of 10: {:b}".format(10))
data = {'city': 'New York', 'temp': 25.5}
print("The temperature in {city} is {temp:.1f}°C.".format(**data))
Demonstrating str.format()
with positional, keyword, and advanced formatting.
flowchart TD A[Start String Formatting] --> B{Choose Method} B -- "Python 3.6+" --> C[f-strings] B -- "Python 3.0+" --> D["str.format()"] B -- "Legacy/C-style" --> E["%-formatting"] C --> C1["Concise, readable, fast"] D --> D1["Flexible, powerful, explicit"] E --> E1["Older, less readable, error-prone"] C1 --> F[End] D1 --> F[End] E1 --> F[End]
Decision flow for choosing a string formatting method in Python.
Legacy: The %
Operator (printf-style Formatting)
The %
operator, often referred to as 'printf-style' formatting, is an older method inherited from C. While still functional in Python 3, it is generally discouraged in new code in favor of f-strings or str.format()
due to its less readable syntax and potential for errors, especially with type mismatches.
name = "David"
points = 88
percentage = 0.885
# Basic usage with different type specifiers
print("Hello, %s! You scored %d points." % (name, points))
# Floating point precision
print("Your percentage is %.1f%%." % (percentage * 100))
# Dictionary mapping
data = {'item': 'Keyboard', 'price': 75.99}
print("The %(item)s costs $%(price).2f." % data)
Examples of string formatting using the legacy %
operator.
%
operator for new code. It's less readable and can lead to TypeError
if the format specifiers don't match the argument types.Choosing the Right Method
With multiple options available, selecting the appropriate string formatting method is crucial for writing clean and maintainable Python code. Here's a quick guide:
- f-strings (Python 3.6+): Use them whenever possible. They are the most modern, readable, and performant option for most formatting tasks.
str.format()
(Python 3.0+): A good alternative if you need to support older Python 3 versions (pre-3.6) or if you prefer the explicit placeholder syntax for very complex formatting scenarios.%
operator: Reserve this for maintaining legacy codebases. Do not use it for new development.

Feature comparison of Python string formatting methods.