brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: textwrap.dedent keeps indented multi-line strings tidy

Scripting
~/tips/tip-python-textwrap-dedent

from textwrap import dedent

Strips shared indentation from a multi-line string so it can sit in indented code.

A triple-quoted string inside an indented function either breaks the layout of your code or drags the indentation into the text. textwrap.dedent removes it.

textwrap.dedent(text) strips the leading whitespace that every line has in common:

from textwrap import dedent

def usage():
    return dedent("""\
        usage: backup.py <source>
          --dry-run  show what would happen
    """)

The result starts at the left edge, and the second line keeps its two extra spaces of relative indent:

usage: backup.py <source>
  --dry-run  show what would happen

The backslash after the opening quotes avoids a blank first line, because it escapes the newline.

Two caveats. Tabs and spaces are not treated as equal, so a block that mixes them has no common prefix and nothing is removed. And with f-strings the order matters. If a value you insert contains a newline, its later lines start at column 0 and ruin the common prefix. For example, a multi-line string placed in an indented f-string comes out with the first line indented and the rest not. Dedent the template first and format afterwards:

dedent("""\
    head
    {}
""").format(multi)

One more thing the docs mention: lines that consist solely of whitespace are normalized to a newline and ignored when working out the margin, so blank lines inside the text do not stop the removal.

Further reading: textwrap.dedent

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil All Scripting tips (10) All topics

Link