Wrap Reports with textwrap and string Helpers
Core idea
textwrap.wrap returns a list of lines for one paragraph; fill joins the lines with newline characters. string provides fixed ASCII constants useful for explicit ASCII policies. Neither module measures actual rendered glyph widths.
from textwrap import wrapprint(wrap("red blue green", width=8))The first two words fit within eight characters.
Dedent and check ASCII digits
from textwrap import dedentimport stringprint(dedent(" A\n B"))print("۷" in string.digits, "۷".isdecimal())dedent removes shared leading whitespace; string.digits contains ASCII digits only.
Common mistake
Do not treat width as terminal-cell width for Persian, combining marks or emoji. Handle layout with a renderer that understands the script.
Practice
Wrap a single ASCII report paragraph at widths 8 and 12; compare the returned lists.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text wrapping
Check your understanding of textwrap and string helpers.
What is printed?
from textwrap import wrapprint(wrap("aa bb", width=3))What is printed?
import stringprint("2" in string.digits, "۲" in string.digits)What does fill return?
Which tool is needed for exact visual layout?