The print() function in Python is versatile and supports multiple formatting strategies to produce clean, readable, and structured output. Understanding these approaches helps developers generate dynamic messages, align data, and integrate values seamlessly.
Basic Output of Primitives and Collections
By default, print() renders built-in types without explicit formatting:
print("qayrup") # Plain string
print(100) # Integer literal
name = "qayrup"
print(name) # Variable reference
items = [1, 2, "a"]
print(items) # List
coords = (1, 2, "a")
print(coords) # Tuple
config = {"a": 1, "b": 2}
print(config) # Dictionary
This works well for debugging or simple display, but real-world applications often require precise control over layout, alignment, and type representation.
Legacy %-Formatting (String Interpolation)
Python’s oldest formatting method resembles C’s printf. It uses the % operator with format specifiers:
message = "(%s) has %d characters" % ("qayrup", len("qayrup"))
print(message) # Output: (qayrup) has 6 characters
Common Format Specifiers
| Specifier | Meaning |
|---|---|
%c |
Single character or ASCII code |
%s |
String conversion |
%d |
Signed decimal integer |
%u |
Unsigned decimal integer |
%o |
Octal integer |
%x |
Lowercase hexadecimal |
%X |
Uppercase hexadecimal |
%f |
Floating-point number (fixed-point) |
%e |
Scientific notation (lowercase e) |
%E |
Scientific notation (uppercase E) |
%g |
Shorter of %f or %e |
%G |
Shorter of %f or %E |
%p |
Memory address (in hex) |
Width, Precision, and Alignment Flags
| Flag | Purpose |
|---|---|
- |
Left-align within field |
+ |
Prefix positive numbers with + |
|
Pad positive numbers with leading space |
# |
Add prefix (0, 0x, etc.) for octal/hex |
0 |
Zero-pad instead of space-padding |
* |
Dynamic width/precision from tuple |
%% |
Literal percent sign |
(key) |
Dictionary key lookup (e.g., %(name)s) |
Numeric Base Conversion Examples
value = 255
print("Hex: %x, Dec: %d, Oct: %o" % (value, value, value))
# Output: Hex: ff, Dec: 255, Oct: 377
Floating-Point Formatting
pi_val = 3.141592653
print("%10.3f" % pi_val) # Width 10, 3 decimals → " 3.142"
print("pi = %.*f" % (4, pi_val)) # Dynamic precision → "pi = 3.1416"
print("%010.3f" % pi_val) # Zero-padded → "000003.142"
print("%-10.3f" % pi_val) # Left-aligned → "3.142 "
print("%+f" % pi_val) # Signed → "+3.141593"
Controlling Line Breaks
By default, print() appends a newline (\n). To suppress it or use custom separators, modify the end paramter:
# Default behavior — each number on new line
for idx in range(6):
print(idx)
# Space-separated on one line
for idx in range(6):
print(idx, end=" ")
# Output: 0 1 2 3 4 5