Python textwrap – How to wrap text in Python

The textwrap module in Python can be used for the wrapping and formatting of text in Python.

Text or “Strings” as they are commonly known, are an important part of any program. Whether it be a simple script or a fully-fledged GUI application, knowing how to handle and format Strings is important. A common issue that occurs when displaying text, is the overflow of text, and uneven-ness of lines due to a varying number of characters in each line.

The Python textwrap module solves these problems, by giving us convenient functions for text wrapping and filling. We will be discussing these functions throughout the rest of this tutorial.


Textwrap Module Functions

There are 5 functions in the Python textwrap module that can be used for the formatting of text. These five functions can be used directly, as we will be doing in this section. Alternatively, they can be used as methods of an object of the TextWrapper Class.

We will have a small section on the TextWrapper Class at the end of this tutorial.

textwrap.shorten

The shorten() function is used to limit the size of a string to a certain number of characters, defined by the width parameter. Useful for preventing overflow of text.

import textwrap

print("This is a long sentence!")
print(textwrap.shorten("This is a long sentence!", width=20))
print(textwrap.shorten("This is a long sentence!", width=10))
This is a long sentence!
This is a long [...]
This [...]

If you want to change the placeholder that appears when the String is overflowing, all you need to do, is use the placeholder option, and pass in the string you want.

import textwrap

print("This is a long sentence!")
print(textwrap.shorten("This is a long sentence!", width=20,
                       placeholder = "...."))
print(textwrap.shorten("This is a long sentence!", width=10,
                       placeholder = "...."))
This is a long sentence!
This is a long....
This....

textwrap.fill

The fill() function in textwrap takes a string as a parameter, and returns a string where each line is of at most 70 characters. 70 is the default value, which is defined by the width parameter.

mytext = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed elit tortor, consequat sit amet sagittis ut, pretium non felis.
Nunc ultricies urna a velit interdum venenatis.
Phasellus sem eros, vehicula in egestas sed, vulputate sit amet ante.
Nulla quis tincidunt nibh, id malesuada erat.
Cras mauris mi, consequat id massa ut, faucibus lacinia lacus.
Nam hendrerit lectus ipsum, eget pharetra tortor aliquet quis.
Sed eu lectus sapien. Nunc interdum diam et sollicitudin tristique.
Pellentesque eget eros sapien."""

print(textwrap.fill(mytext, width = 70))

You can see how uniform the output is, as compared to the original string.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit
tortor, consequat sit amet sagittis ut, pretium non felis. Nunc
ultricies urna a velit interdum venenatis. Phasellus sem eros,
vehicula in egestas sed, vulputate sit amet ante. Nulla quis tincidunt
nibh, id malesuada erat. Cras mauris mi, consequat id massa ut,
faucibus lacinia lacus. Nam hendrerit lectus ipsum, eget pharetra
tortor aliquet quis. Sed eu lectus sapien. Nunc interdum diam et
sollicitudin tristique. Pellentesque eget eros sapien.

Additional Parameters

The fill() and wrap() functions actually have a lot of options as parameters. Let’s take a brief look through all of them.

width: (Default value: 70). The maximum possible length of any line. If any individual word is larger than the limit, it the excess characters get moved to the next line (unless break_long_words is set to False, in which case they get a new line)

expand_tabs: (Default value: True) If value is set to true, then all tab characters in text parameter will be expanded to spaces.

tab_size: (Default value: 8) Determines how many spaces if a tab expanded to, if the expand_tabs option is set to True. (Does not accept negative values).

replace_whitespace: (Default value: True) When this option is true, after tab expansion but before wrapping, the wrap() function replaces each whitespace character with a single space. The whitespace characters that get replaced are the following: tab ('\t'), newline ('\n'), vertical tab ('\v'), formfeed ('\f'), and carriage return ('\r')

drop_whitespace: (Default value: True) When this option is true, any whitespace at the beginning and ending of every line (after wrapping but before indenting) is dropped. An empty string will not be effected.

fix_sentence_endings: (Default value: False) If this option is True, then it will attempt to detect sentence endings and ensure that sentences are always separated by exactly two spaces. This is generally desired for text in a monospaced font. However, the sentence detection algorithm is imperfect, and may not work as desired in specific situations.

break_long_words: (Default value: True) If set to True, then any words longer than the max allowed width , will be broken down to ensure all lines fit. Otherwise if option is set to False, words longer than width will be placed on a new line.

break_on_hyphens: (Default value: True) If this option’s value is True, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. If option is set to False, then only whitespaces will be considered as potentially good places for line breaks, but you need to set the break_long_words option to false if you want truly insecable words.

initial_indent: (Default value: ' ') Defines the string that will be prepended to the first line of the output. The indent counts towards the length of the first line.

max_lines: (Default value: None) Restricts the output to at most max_lines. Adds a placeholder at the end.

placeholder: (Default value: " [...]“) Defines the string that will appear at the end of the output if it has been truncated.


textwrap.wrap

The wrap() function is almost identical (same parameters) to fill(), with one exception. It returns a list of strings, instead of a single string. Each string in the list of strings, represents a single line.

mytext = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed elit tortor, consequat sit amet sagittis ut, pretium non felis.
Nunc ultricies urna a velit interdum venenatis.
Phasellus sem eros, vehicula in egestas sed, vulputate sit amet ante.
Nulla quis tincidunt nibh, id malesuada erat.
Cras mauris mi, consequat id massa ut, faucibus lacinia lacus.
Nam hendrerit lectus ipsum, eget pharetra tortor aliquet quis.
Sed eu lectus sapien. Nunc interdum diam et sollicitudin tristique.
Pellentesque eget eros sapien."""

lines = textwrap.wrap(mytext)

for line in lines:
    print(line)
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit
tortor, consequat sit amet sagittis ut, pretium non felis. Nunc
ultricies urna a velit interdum venenatis. Phasellus sem eros,
vehicula in egestas sed, vulputate sit amet ante. Nulla quis tincidunt
nibh, id malesuada erat. Cras mauris mi, consequat id massa ut,
faucibus lacinia lacus. Nam hendrerit lectus ipsum, eget pharetra
tortor aliquet quis. Sed eu lectus sapien. Nunc interdum diam et
sollicitudin tristique. Pellentesque eget eros sapien.

As you can see, iterating over the list and printing them gives the same output as the fill() function.


textwrap.indent()

The indent() function is a handy way of adding in some indentation (whitespace), or even customer characters before the start of every line in the string.

mytext = """\
Hello
World,
Good
Morning!\n"""

print(mytext)

print(textwrap.indent(mytext, '   '))

print(textwrap.indent(mytext, '->'))
Hello
World,
Good
Morning!

   Hello
   World,
   Good
   Morning!

->Hello
->World,
->Good
->Morning!

The prefix is only added to lines which do not entirely consist of whitespaces.


textwrap.dedent

The multi-line string in the below example may seem normal to you, but to Python, the string has been indented quite a bit. Printing out this string will not give you the output you expect, as there will be alot of whitespace due to the indentation.

Using the dedent() function here, will remove the common leading whitespace (the whitespace before the line with the least indentation). So if the line with “Hello” has 10 whitespaces before it, all of the lines will have 10 whitespaces removed.

# end first line with \ to avoid an empty line
string = '''\
         Hello
             World
         '''

print(repr(string))   
print(repr(textwrap.dedent(string))) 
'         Hello\n             World\n         '
'Hello\n    World\n'

Using the TextWrapper Class

The TextWrapper Class is the recommended approach to using the textwrap module if you require more than 1 or 2 function calls. Instead of directly calling the functions each time, you should first create the TextWrapper object, define it’s settings, and then pass the string into it.

The benefit of using TextWrapper, is that you can pre-define all the settings on your TextWrapper object, and then use the required function, without having to redefine the parameter values. Only two functions are actually available with TextWrapper, fill() and wrap().

s1 = "This is a sentence!"
s2 = "This is an even longer sentence!"

# Method 1
print(textwrap.fill(s1, width = 10))
print(textwrap.fill(s2, width = 10))

# Method 2
wrapper = textwrap.TextWrapper(width = 10)

print(wrapper.fill(s1))
print(wrapper.fill(s2))

Both of these methods do the same thing, but the second approach only requires you to define the parameters once. This is especially useful if you are using 4-5 parameters for the fill() or wrap() function.


This marks the end of the Python textwrap Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments