Python print() Function: Parameters, f-strings, and Output Control
Summary
Section titled “Summary”print() is a built-in function that writes to sys.stdout by default. It is the standard tool for quick console output and debugging in scripts. For application code, prefer the logging module — it adds levels, timestamps, and routing to files without changing your code.
# Save as print_examples.py and run with:python print_examples.pySyntax
Section titled “Syntax”print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)| Parameter | Default | Purpose |
|---|---|---|
*objects |
— | One or more values to print |
sep |
' ' |
Separator between multiple values |
end |
'\n' |
Appended after the last value |
file |
sys.stdout |
Output stream |
flush |
False |
Flush the stream immediately if True |
Basic usage
Section titled “Basic usage”print("Hello, world!")# Hello, world!
print(42)print(3.14)print(True)print(None)# 42# 3.14# True# None
# Multiple values — separated by a spaceprint("Order", "ORD-001", "confirmed")# Order ORD-001 confirmedsep: custom separator
Section titled “sep: custom separator”# Default separator is a spaceprint("2026", "11", "13", sep="-")# 2026-11-13
print("ORD", "001", sep="")# ORD001
# CSV-style outputprint("ORD-001", "BensonCo", "149.99", sep=",")# ORD-001,BensonCo,149.99
print("a", "b", "c", sep=" | ")# a | b | cend: control line ending
Section titled “end: control line ending”# Default end is a newline \nprint("Processing...", end=" ")print("Done.")# Processing... Done.
# Progress display — overwrite the same lineimport timefor i in range(1, 4): print(f"\rProcessing order {i}/3", end="", flush=True) time.sleep(0.5)print() # final newlinef-strings: the preferred way to format output
Section titled “f-strings: the preferred way to format output”f-strings (Python 3.6+) are the standard for string interpolation:
order_id = "ORD-001"customer = "BensonCo"amount = 149.99
print(f"Order {order_id} for {customer}: ${amount:.2f}")# Order ORD-001 for BensonCo: $149.99
# Alignmentprint(f"{'Item':<20} {'Qty':>5} {'Price':>10}")print(f"{'Widget':<20} {12:>5} {29.99:>10.2f}")# Item Qty Price# Widget 12 29.99
# Debug: f-string with = prints the expression and its valuex = 42print(f"{x=}") # x=42print(f"{x*2=}") # x*2=84
# Thousands separatortotal = 1_234_567.89print(f"{total:,.2f}") # 1,234,567.89
# Percentageratio = 0.837print(f"{ratio:.1%}") # 83.7%file: writing to stderr or a file
Section titled “file: writing to stderr or a file”import sys
# Write to stderr (shown in red in most terminals)print("Error: order not found", file=sys.stderr)
# Write to a filewith open("output.log", "w", encoding="utf-8") as f: print("ORD-001 processed", file=f) print("ORD-002 skipped", file=f)flush: immediate output
Section titled “flush: immediate output”Normally, Python buffers writes. flush=True forces the buffer to be written immediately — important for real-time progress bars or when the output is piped:
import timeimport sys
for i in range(5): print(f"Step {i+1}/5", end="\r", flush=True) time.sleep(0.3)print()Printing collections
Section titled “Printing collections”orders = ["ORD-001", "ORD-002", "ORD-003"]print(orders) # ['ORD-001', 'ORD-002', 'ORD-003']print(*orders) # ORD-001 ORD-002 ORD-003 (unpacked)print(*orders, sep="\n") # one per line
order = {"id": "ORD-001", "amount": 149.99}print(order) # {'id': 'ORD-001', 'amount': 149.99}
import jsonprint(json.dumps(order, indent=2)) # pretty-printed JSONWhen to use logging instead of print
Section titled “When to use logging instead of print”print() is fine for scripts and quick debugging. For application code that runs in production, use the logging module:
import logging
logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s — %(message)s",)logger = logging.getLogger(__name__)
logger.info("Order %s confirmed", "ORD-001")logger.warning("Retry %d for order %s", 2, "ORD-002")logger.error("Payment failed for order %s", "ORD-003")logging gives you levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), timestamps, source module names, and the ability to route output to files, remote systems, or structured JSON — none of which print() supports.
Common mistakes
Section titled “Common mistakes”- Using
print()in production application code. It goes to stdout without timestamps, levels, or routing. Uselogging. - Not flushing in long-running scripts. If stdout is redirected to a file, unbuffered output may not appear until the script ends. Use
flush=Trueor run Python with-u(unbuffered). - Formatting numbers with string concatenation.
"Total: " + str(amount)is harder to read thanf"Total: {amount:.2f}".
Key takeaways
Section titled “Key takeaways”sepcontrols the separator between values;endcontrols what follows the last value.- f-strings are the standard for string interpolation;
{value:.2f}controls decimal places. - Use
file=sys.stderrto write error output to stderr. - Use
flush=Truefor real-time progress output. - Use
logginginstead ofprint()in any code that runs unattended.
Official references
Section titled “Official references”- Python docs: print() — full parameter reference
- Python docs: f-strings — PEP 701 format spec
- Python docs: Format Specification Mini-Language — alignment, precision, thousands separator