← retour aux snippets

textwrap: dedent et formatage de paragraphes

Nettoyer l'indentation et enrouler le texte à une largeur cible.

python text #textwrap#dedent#wrap

objectif

Nettoyer l’indentation et enrouler le texte à une largeur cible.

code minimal

import textwrap
raw = "    ligne 1\n        ligne 2 indentee\n"
cleaned = textwrap.dedent(raw)
print(cleaned.startswith("ligne 1"))  # attendu: True

utilisation

import textwrap
para = "Les fonctions de textwrap permettent de formater proprement un paragraphe long."
out = textwrap.fill(para, width=40)
print(all(len(l) <= 40 for l in out.splitlines()))

variante(s) utile(s)

import textwrap
s = "mot " * 10
print(textwrap.shorten(s, width=12, placeholder="...").endswith("..."))

notes

  • dedent retire l’indentation commune; pratique pour les docstrings.
  • fill et wrap contrôlent précisément la largeur des lignes.