Textwrap — Wrapping and filling text in Python

Python Methods and Functions

TextWrapper instance attributes (and keyword arguments to constructor):

  • width: refers to the maximum allowed length of wrapped lines. The default is 70.
  • expand_tabs: The default is TRUE. If true, then all tabs in the sample input are expanded to spaces using this method.
  • tabsize: its default value is 8. This method expands all tabs up to zero or more spaces in the text, depending on the current column and the specified tab size, if expand_tabs is TRUE.
  • replace_whitespace: its default value is TRUE. If true, after expanding a tab but before wrapping, the wrap () method replaces each space character with a single space. These space characters are replaced: tab, newline, vertical tab, line feed, and carriage return (& # 39; / t / n / v / f / r & # 39;).
  • drop_whitespace : its default is TRUE. Spaces at the beginning and end of each line (after hyphenation, but before indentation) are removed if the value is set to TRUE.
  • initial_indent: The default is & # 39; & # 39 ;. This method appends the specified line to the first hyphen.
  • subsequent_indend: this default is & # 39; & # 39 ;. This method appends the given line to all lines of the wrapped output except the first.
  • placeholder: its default value is set to "[...]". This method appends a line to the end of the output text if it has been truncated.
  • max_lines: This is set to None by default. If the value is not None, then the output text contains no more than max_lines lines with placeholders at the end of the output.
  • break_long_words: The default is True. If TRUE, words longer than the width are split to fit each line in the given width. If it is FALSE, long words will not be broken and will be placed on the line by themselves to minimize the amount of over-width.
  • break_on_hyphens: is set to True by default. If the value is TRUE, hyphenation occurs in spaces and immediately after the hyphen in compound words. If the value is FALSE, line breaks only occur in spaces, but you need to set break_long_words to FALSE if you want truly unprotected words.

Functions provided by the Textwrap module:

  1. textwrap.wrap (text, width = 70, ** kwargs) : This function wraps the input paragraph so that the length of each line in the paragraph is not more width. The wrap method returns a list of output lines. The returned list will be empty if the packed output has no content. The default width is 70.

    import textwrap

     

    value = & quot; & quot; & quot; This function wraps the input paragraph so that each line

    in the paragraph has the maximum length of characters. The wrapping method
    returns a list of output lines. The returned list
    is empty if the wrapped
    output has no content.

     
    # Wrap this text.

    wrapper = textwrap.TextWrapper (width = 50 )

     

    word_list = wrapper.wrap (text = value)

     
    # Print each line.

    for element in word_list:

      print (element)

    Output:

     This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. 
  2. textwrap.fill (text, width = 70, ** kwargs): the convenient fill () function works like textwrap.wrap, except that it returns data concatenated into a single line separated by a newline character. This function wraps one input paragraph into text and returns a single line containing the paragraph to be wrapped.

    import textwrap

     

    value = & quot; & quot; "This function returns the response as STRING, not LIST." & quot; & quot;

     
    # Wrap this text.

    wrapper = textwrap.TextWrapper (width = 50 )

      

    string = wrapper .fill (text = value)

      

    print (string)

    Output:

     This function returns the answer as STRING and not LIST ... 
  3. textwrap.dedent (text) : This function is used to remove any common leading white space from every line of the input text. This allows document lines or inline multiline lines to match the left edge of the screen while removing the formatting from the code itself.

    Example:

    import textwrap

      

    wrapper = textwrap.TextWrapper (width = 50 )

     

    s = & # 39; & # 39; & # 39; /

    Hello

    World

    " ""

    print ( repr (s)) # prints & # 39; hello / world n / n & # 39;

     

    text = textwrap.dedent (s)

    print ( repr (text)) # prints & # 39; hello / world n / n & # 39;

    Output:

     'hello world' 'hello world' 
  4. textwrap.shorten (text, width, ** kwargs) : This function truncates the input string so that the length of the string is equal to the specified width. First, all spaces in the string are collapsed by removing spaces with one space. If the modified string fits into the given string, it is returned; otherwise, the trailing characters are removed so that the remaining words plus placeholder fit within the width.

    import textwrap

     

    sample_text = & quot; & quot; & quot; This function wraps the input paragraph so that each line

    n must not exceed the width of the paragraph. The wrapping method
    returns a list of output lines. The returned list
    is empty if the wrapped
    output has no content.

     

    wrapper = textwrap.TextWrapper (width = 50 )

     

    dedented_text = textwrap.dedent (text = sample_text)

    original = wrapper.fill (text = dedented_text)

     

    print ( 'Original:' )

    print (original)

     

    shortened = textwrap.shorten (text = original, width = 100 )

    shortened_wrapped = wrapper.fill (text = shortened)

     

    print ( 'Shortened:' )

    print (shortened_wrapped)

    Output:

     Or iginal: This function wraps the input paragraph such that each line n the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Shortened: This function wraps the input paragraph such that each line n the paragraph is at most width [...] 
  5. textwrap.indent (text, prefix, predicate = no) : This function is used to add the given prefix to the beginning of the selected lines of text. The predicate argument can be used to control which lines are indented.

    import textwrap

     

    s = 'hello world'

    s1 = textwrap.indent (text = s, prefix = '' )

     

    print (s1)

    print ( " " )

     

    s2 = textwrap.indent (text = s, prefix = '+' , predicate = lambda line: True )

    print (s2)

    Output:

     hello world + hello + + + world 
  6. This article is courtesy of Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.