Wrap Text To A Specific Character Length In Python

Use textwrap.fill(STRING, LENGTH) to wrap text to a specific character length in python.


The [textwrap module] offers a bunch of other functions as well:

- wrap - outputs a list with no newlines - fill - returns the single string - shorten - truncates with an optional `...` type string - dedent - remove leading whitespace - indent - add whitespace

There is also textwrap.TextWrapper which has:

- width - The maximum length of wrapped lines - expand_tabs - All tab characters in text will be expanded to spaces - tabsize - All tab characters in text will be expanded to zero or more spaces - replace_whitespace - After tab expansion but before wrapping, the wrap() method will replace each whitespace character with a single space - drop_whitespace - Whitespace at the beginning and ending of every line (after wrapping but before indenting) is dropped - initial_indent - String that will be prepended to the first line of wrapped output - subsequent_indent - String that will be prepended to all lines of wrapped output except the first - fix_sentence_endings - Attempt to detect sentence endings and ensure that sentences are always separated by exactly two spaces - break_long_words - Words longer than width will be broken in order to ensure that no lines are longer than width - break_on_hyphens - Wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English - max_lines - the output will contain at most max_lines lines, with placeholder appearing at the end of the output - placeholder - String that will appear at the end of the output text if it has been truncated - wrap - Wraps the single paragraph in text (a string) so every line is at most width characters long and returns a list - fill - Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph