Format Python code

Format Python with consistent four-space indentation and readable line breaks.

freeworks offlinenothing uploaded
ToolPython Formatter
Input
Output
Put this on your own site

The frame below runs the same code as this page, in the reader's own browser. Nothing is sent to us, and nothing is sent to you.

Pick a dark background and the text and panels follow it, so the frame stays readable on a dark page.

Preview

How it works

Python tokens are indented from colon-delimited suites while strings, comments, brackets, and continuation lines are preserved. Formatting changes layout without executing code.

  • PEP 8 recommends four spaces.
  • Open brackets and continuations allow readable multiline expressions.

Worked example

Format Python code
Fix indentation in a Python function
Input
											def greet(name):
  if name:
    print(f'Hello {name}')
  else:
    print('Hello World')
										
Output
												def greet(name):
    if name:
    print(f'Hello {name}')
    else:
    print('Hello World')
											

When to use this

Pre-commit hooks, notebook exports, and code reviews format Python.

Edge cases

  • A colon inside a string is not a suite delimiter.
  • Triple-quoted strings preserve embedded indentation.
  • Backslashes and open brackets continue a statement without a new block.

References