How to add Python code to a Word document with colours

Python's indentation-sensitive syntax makes Word pasting especially painful. Lose the spaces and your code is syntactically broken. Here's how to paste Python into Word with correct indentation, IDE colours and monospace fonts — every time.

Why Python is harder than other languages

Most languages use braces {} or keywords to define code blocks. Python uses indentation. If you lose the spaces when pasting, the code doesn't just look wrong — it's actually broken. A reader will get IndentationError immediately.

The indentation problem: When Word receives pasted HTML, it collapses multiple consecutive spaces into one. A 4-space Python indent becomes 1-space. An 8-space nested block becomes 2 spaces. The visual hierarchy of your code is destroyed.

The only fix is to replace spaces with non-breaking spaces (\u00A0) before pasting. Word treats them as content, not formatting — so they're preserved. FormatCode does this automatically.

What Python code looks like with proper highlighting

# DEVICE MANAGER

class DeviceManager:
    """Persist device metadata."""

    def __init__(self) -> None:
        self._devices: dict = self._load()

    def add(self, name: str) -> dict:
        if name in self._devices:
            raise ValueError(f"Device '{name}' exists")
        return {"name": name}

Python colour scheme in FormatCode

Blue — keywords (if, for, while, import)
Teal — class names, type hints
Yellow — function and method names
Light blue — parameters, variables, self
Orange — strings and f-strings
Light green — numbers
Green — comments and docstrings
Cyan — built-ins (print, len, range)

Step-by-step: paste Python into Word

  1. Open formatcode.app
  2. Paste your Python code into the left panel
  3. Select Python from the language dropdown
  4. Choose the VS Code Dark+ background swatch (dark grey)
  5. Click Copy for Word
  6. In Word, press Ctrl+V — choose Keep Source Formatting

Indentation tip: FormatCode converts every space to a Unicode non-breaking space before copying. 4-space indents, 8-space nested blocks, and multi-line dict alignment are all preserved exactly.

Format your Python code now

Free tool. No signup. Python code to Word in under 30 seconds.

Open FormatCode →