The print()
function is your gateway to displaying information in Python programs. While it seems simple at first, Python 3 offers several ways to format your output for better readability, clarity, and even dynamic content. This article delves into these formatting techniques, helping you craft informative and visually appealing output.
1. Basic String Formatting (String Concatenation)
The most basic approach involves string concatenation using the +
operator. You can combine strings, variables, and expressions to create the desired output:
name = "Alice"
age = 30
# Simple concatenation
print("Hello, " + name + "! You are", age, "years old.")
# Using commas for automatic separation with spaces
print("Hello,", name, "! You are", age, "years old.")
This method is straightforward but becomes cumbersome for complex outputs.
2. Format Specifiers (%
formatting)
Python 3 offers formatted string literals using the %
operator (similar to C-style formatting). You place placeholders (%s
, %d
, etc.) within a string and provide values to be inserted:
name = "Bob"
age = 25
print("Hello, %s! You are %d years old." % (name, age))
Here are common format specifiers:
%s
: String%d
: Integer%f
: Floating-point number
Caution: While still functional, %
formatting is considered less Pythonic and might be deprecated in future versions.
3. f-strings (Formatted String Literals) – The Modern Way (Python 3.6+)
Introduced in Python 3.6, f-strings (formatted string literals) are the recommended and most versatile way to format strings. They embed expressions directly within curly braces {}
:
Python
name = "Charlie"
age = 42
print(f"Hello, {name}! You are {age} years old.")
F-strings provide several benefits:
- Cleaner syntax compared to
%
formatting. - Ability to embed expressions and perform calculations within the string.
- Support for f-string formatting options like alignment and precision control.
Example with formatting options:
pi = 3.14159
radius = 5
# Format with two decimal places and right-align in 10 characters
print(f"Area of circle: {pi * radius**2:.2f} (radius = {radius:>10})")
This prints:
Area of circle: 78.53 (radius = 5)