How to Format Output in Python: Syntax and Examples
In Python, you can format output using
f-strings by placing expressions inside curly braces within a string prefixed with f. Alternatively, use the format() method or the older % operator for string formatting.Syntax
Python offers several ways to format output strings:
- f-strings: Use
f"text {variable}"to embed expressions directly. - format() method: Use
"text {}".format(value)to insert values. - Percent (%) formatting: Use
"text %s" % value(older style, less recommended).
Each method allows you to control how values appear in the output.
python
name = "Alice" age = 30 # f-string print(f"Name: {name}, Age: {age}") # format() method print("Name: {}, Age: {}".format(name, age)) # Percent formatting print("Name: %s, Age: %d" % (name, age))
Output
Name: Alice, Age: 30
Name: Alice, Age: 30
Name: Alice, Age: 30
Example
This example shows how to format numbers with decimals and align text using f-strings.
python
price = 49.99 quantity = 5 # Format price with 2 decimals print(f"Price: ${price:.2f}") # Align quantity right in 3 spaces print(f"Quantity: {quantity:>3}") # Combine text and calculations total = price * quantity print(f"Total: ${total:.2f}")
Output
Price: $49.99
Quantity: 5
Total: $249.95
Common Pitfalls
Common mistakes when formatting output include:
- Using the old
%formatting which is less readable and flexible. - Forgetting to prefix strings with
fwhen using f-strings, causing variables to print literally. - Incorrect format specifiers causing errors or wrong output.
python
# Wrong: missing f prefix name = "Bob" print("Hello, {name}!") # prints literally # Right: with f prefix print(f"Hello, {name}!")
Output
Hello, {name}!
Hello, Bob!
Quick Reference
| Method | Syntax Example | Description |
|---|---|---|
| f-string | f"Name: {name}" | Embed expressions directly, modern and preferred |
| format() | "Name: {}".format(name) | Insert values using placeholders |
| Percent (%) | "Name: %s" % name | Older style, less flexible |
Key Takeaways
Use f-strings for clear and concise output formatting in Python 3.6+.
The format() method is useful for older Python versions or complex formatting.
Avoid the old % formatting style for new code.
Always prefix strings with f when using f-strings to embed variables.
Use format specifiers to control number precision and text alignment.