Dup Ver Goto 📝

Python's stdlib textwrap module

To
43 lines, 141 words, 1161 chars Page 'TextWrap1' does not exist.

The official docs

textwrap.wrap(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

Example

This is a short command that wraps the input text and possibly adds leading >s – its purpose is to turn text into a Markdown block comment.

#!/usr/bin/env python
import textwrap
import sys
import os
args = sys.argv[1:]

def main(n=0,c='>'):
  w = os.getenv("W",72)
  try:
    w = int(w)
  except ValueError:
    w = 72
  try:
    n = int(n)
  except ValueError:
    print(f"Error: first parameter '{n}' must be an integer",file=sys.stderr())
    exit(1)
  a = sys.stdin.read().strip()
  if n > 0:
    f = " ".join([c]*n+[''])
  else:
    f = ""
  b = textwrap.fill(a,w,initial_indent=f,subsequent_indent=f)
  print(b)

if __name__ == "__main__":
  exit(main(*args))

and then I wrap this in

#!/bin/bash
pp | twrap "$@" | pc

where twrap is the above script, pp pastes and pc copies.