Python
print
bold text
text formatting
Python tips

How can I print bold text in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Printing bold text in Python depends on the output environment, not just Python itself. Terminals, notebooks, and log files each handle styling differently. A robust solution detects capabilities, applies styles only when supported, and falls back to plain text for non-interactive outputs.

ANSI Escape Codes for Terminal Output

In most modern terminals, bold is represented with ANSI code 1 and reset with 0.

python
1BOLD = "\033[1m"
2RESET = "\033[0m"
3
4print(f"{BOLD}Build succeeded{RESET}")
5print("normal line")

Always reset style after the bold segment. If you forget reset, later lines may stay styled unexpectedly.

Simple helper function

python
1def bold(text: str) -> str:
2    return f"\033[1m{text}\033[0m"
3
4print(bold("Important"))

This works well for lightweight scripts and internal command line tools.

Windows Compatibility with colorama

ANSI support can vary across Windows terminals. colorama normalizes behavior.

python
1from colorama import init, Style
2
3init(autoreset=True)
4print(Style.BRIGHT + "Task complete")
5print("normal output")

autoreset=True is useful because it avoids manual reset for every line.

Rich Text for Production CLI Tools

For advanced command line interfaces, rich is easier to maintain than raw ANSI strings.

python
1from rich.console import Console
2
3console = Console()
4console.print("[bold]Deployment finished[/bold]")
5console.print("[bold red]Error:[/bold red] invalid token")

rich also supports tables, progress bars, and syntax highlighting, which keeps output consistent across commands.

Support Plain Mode for Logs and Redirected Output

Styled output is often undesirable in files, CI artifacts, or machine-parsed logs. Use a style toggle:

python
1import os
2import sys
3
4
5def supports_style() -> bool:
6    if os.getenv("NO_COLOR"):
7        return False
8    return sys.stdout.isatty()
9
10
11def maybe_bold(text: str) -> str:
12    if supports_style():
13        return f"\033[1m{text}\033[0m"
14    return text
15
16print(maybe_bold("Sync complete"))

This pattern prevents control characters from polluting stored logs.

Jupyter and Notebook Context

ANSI codes may not render as expected in notebook outputs. In notebooks, prefer Markdown display for emphasis.

python
from IPython.display import Markdown, display

display(Markdown("**Training complete**"))

Do not assume notebook rendering matches terminal behavior.

Design Output Semantics, Not Just Formatting

Bold should support meaning, not replace it. Pair style with explicit labels such as ERROR, WARN, or SUCCESS so meaning survives when style is disabled.

Good:

text
ERROR: Failed to connect to database

Weak:

text
same message in bold only

Semantic text keeps accessibility and machine processing intact.

Test Matrix You Should Use

Before shipping CLI styling, verify behavior in:

  • macOS Terminal and Linux shell.
  • Windows PowerShell and Windows Terminal.
  • CI logs with redirected output.
  • notebook environment if applicable.

A quick local check for control characters in logs:

bash
python app.py > output.log
cat -v output.log

If escape sequences appear, disable style when stdout is not a tty.

Centralize Styling in One Utility

As tools grow, avoid scattering style literals through command handlers. Put styling decisions in one utility so behavior stays consistent for all commands and tests.

python
1class Formatter:
2    def __init__(self, enabled: bool):
3        self.enabled = enabled
4
5    def bold(self, msg: str) -> str:
6        if not self.enabled:
7            return msg
8        return f"\\033[1m{msg}\\033[0m"
9
10fmt = Formatter(enabled=True)
11print(fmt.bold("Release complete"))

This also makes it easy to add new styles without touching business logic.

Common Pitfalls

  • Using ANSI codes without reset and leaking style to later lines.
  • Assuming all Windows environments render ANSI sequences identically.
  • Writing styled output into machine-parsed logs.
  • Relying on bold alone to communicate severity.
  • Ignoring plain-text fallback for non-interactive execution.

Summary

  • Bold text in Python is environment-dependent, not universally handled by print.
  • ANSI escape codes are simple and effective in many terminals.
  • 'colorama improves compatibility, especially on Windows.'
  • 'rich is better for larger CLI applications with structured output.'
  • Always provide a plain-text fallback for logs and automation workflows.

Course illustration
Course illustration

All Rights Reserved.