HomeToolsFormattingPython Code Formatter

Python Code Formatter

Format Python code scripts matching standard PEP 8 spacing styling patterns.

Formatting
Raw Code
Formatted Code

Read this before changing Python indentation

Python uses indentation as syntax, not decoration. Moving a statement one level can change which branch executes, which loop owns it, or whether a definition contains it at all. That makes a Python Code Formatter fundamentally different from a brace-language beautifier: reliable reformatting requires parsing valid Python and preserving its block structure.

This page provides a deliberately simple line-layout utility. It trims each non-empty line, removes blank lines, and reapplies either two or four spaces according to a small set of bracket-oriented indentation rules. It does not recognize colons as Python suite openers. Consequently, it is useful for cleaning leading whitespace in bracketed data fragments or experimenting with indentation width, but it does not implement Black, Ruff format, autopep8, YAPF, or complete PEP 8 formatting. Knowing that boundary prevents a neat-looking output pane from being mistaken for validated Python.

What the current formatter detects

Every input line is stripped of leading and trailing whitespace. Empty lines are skipped. Before writing a line, indentation decreases when the trimmed line begins with }, ], or </. After writing it, indentation increases when the line ends in { or [. There is also generic handling for certain tag-like lines. The selected two- or four-space width is multiplied by the current level.

These rules can make a list split across lines more regular:

records = [
 {"id": 1},
   {"id": 2},
]

With four spaces selected, the result is:

records = [
    {"id": 1},
    {"id": 2},
]

However, ordinary Python blocks are introduced by a colon, and the formatter does not increase indentation after def, class, if, for, while, try, with, or match statements. For example:

def total(values):
return sum(values)

remains aligned at the left edge rather than becoming a valid function body. The tool cannot infer the intended suite, and it should not pretend to do so.

A narrow, responsible way to use it

Begin with a copy, especially if the input already runs. Paste a short fragment into Raw Code, select two or four spaces, and compare every line in Formatted Code. Use Copy only when the result’s structure is obvious from brackets or when you intend to adjust block indentation manually in an editor.

After any change, run Python’s parser or compiler on the file. A simple python -m py_compile path/to/file.py catches syntax and indentation errors for one file; the project’s test command provides behavioral confidence. Then run the repository’s actual formatter and linter. If the project uses Black or Ruff, their configuration and target version should be the authority.

Do not paste a complete module merely to convert four-space indentation to two spaces. PEP 8 recommends four spaces per indentation level, and many Python tools enforce that convention. The two-space choice can still be useful for a display-only example or data-like fragment, but it is rarely suitable for committed Python suites.

The output updates as input or indentation width changes. Copy writes the generated text to the clipboard. There is no download operation, syntax report, AST preview, or error list. An empty or whitespace-only input produces empty output.

What a full Python formatter normally handles

A parser-backed Python formatter understands logical lines rather than treating each physical line independently. It can preserve suites after colon-terminated headers, indent continuation lines inside parentheses, keep decorators attached to definitions, and recognize comprehensions, lambdas, annotations, f-strings, comments, and multiline strings.

It also makes explicit style decisions. Black normalizes spacing, line breaks, quote forms in selected situations, trailing commas, and collection layout while targeting stable diffs. Ruff’s formatter follows a Black-compatible style with its own documented differences and integrates with linting. autopep8 focuses on fixes derived from pycodestyle diagnostics. Those tools still require tests, but they operate with far more grammatical context than line trimming.

PEP 8 is a style guide rather than a complete printing algorithm. “PEP 8 formatter” can imply many choices the guide leaves open, including line breaking and project exceptions. This page does not check line length, spaces around operators, blank lines between definitions, import grouping, naming conventions, docstrings, or trailing whitespace separately. It removes blank lines altogether, which is often contrary to readable Python module structure.

Syntax that is especially vulnerable

Multiline strings preserve exact text between triple quotes, including indentation that may be consumed by an application or shown to a user. Since this formatter trims each physical line, it can alter string contents. The same warning applies to doctests, embedded SQL, templates, shell scripts, and expected-output fixtures inside strings.

Comments may need indentation to remain associated with a block, and formatting directives such as # fmt: off, # noqa, type-checker comments, and coverage pragmas have tool-specific meaning. Trimming and removing blank lines can change their context or make a file harder to understand.

Continuation indentation inside parentheses is flexible, but closing ) is not one of the tokens that lowers this formatter’s indentation level. Parenthesized calls and tuples therefore do not receive balanced indentation behavior comparable to square brackets. Dictionary braces may change levels when placed at line ends, yet a closing brace only dedents when it starts a line. Inline structures offer little signal.

Python 3.10 pattern matching, asynchronous constructs, exception groups, positional-only parameters, type parameter syntax, and nested f-string grammar all require awareness of the selected Python version. This tool neither chooses a version nor parses these features.

Recovering from damaged indentation

If you only possess badly indented Python, avoid guessing across an entire file. First search version control, package artifacts, editor history, deployed source maps or images, and backups for an intact copy. Syntax errors identify where parsing fails but cannot always reveal the author’s intended block ownership.

Work function by function. Use tests and call sites to understand control flow, then reconstruct suites in an editor that shows whitespace. Run the parser after each small repair. Static type checking and lint rules can expose unreachable code, undefined names, and suspicious branch structure, but human review remains necessary.

If output from this page removed meaningful blank lines or multiline-string indentation, discard it and return to the untouched source. Do not try to reverse the transformation from the generated pane: trimmed whitespace is no longer available there.

Common surprises explained

A function body did not indent. Colon-ended Python headers are not part of the current indentation logic. Add the correct indentation manually or use a Python parser-based formatter on valid source.

Blank lines disappeared. Empty trimmed lines are intentionally skipped by the implementation. This includes spacing between top-level definitions.

A triple-quoted string changed. Each physical line is trimmed without string awareness. Restore the source immediately; exact string content may have been lost.

A list looks better but its surrounding if block does not. Square brackets affect the tracked level, while Python suites do not. The formatter is bracket-oriented rather than Python-grammar-oriented.

Two spaces passes the formatter but fails project checks. The selector controls output width only. It does not certify PEP 8 conformance, and the project probably requires four spaces.

Python Code Formatter FAQ

Does this tool make invalid Python valid?

No. It neither repairs syntax nor reports parser errors. It may produce text that still raises IndentationError or changes behavior.

Is the output PEP 8 compliant?

Not in a comprehensive sense. PEP 8 covers far more than choosing two or four spaces, and ordinary suite indentation is not inferred here.

Can it replace Black or Ruff format?

No. Use those tools for syntax-aware, reproducible project formatting. This utility is best treated as a small line-layout scratchpad.

Why offer two spaces for Python?

It can suit display snippets or bracketed data, and some nonstandard environments use it. Conventional Python projects overwhelmingly prefer four spaces per indentation level.

Are comments and blank lines preserved?

Non-empty comment lines remain as trimmed text, but their indentation may change. Blank lines are removed.

What verification is essential?

Compare against the original, compile or parse the file with the target Python version, run the canonical formatter and linter, execute tests, and inspect the diff for changed strings or block ownership.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →