Updated On : Mar-06,2021 Time Investment : ~15 mins

textwrap - Simple Guide to Wrap and Fill Text in Python

Python developers work with strings every now and then. Many situations require the string to be wrapped in order to improve visibility or other reasons. Developers might need to wrap text because size to prevent overflowing beyond the size of the screen commonly. The websites with blogs or articles need to wrap text based on screen size. The wrapping string simply based on a number of characters per line will result in the breaking of the words. We need a way to wrap text so that it does not break words and wrapping looks natural. Python provides us with a module named textwrap for this purpose. It provides different methods to wrap long text. As a part of this tutorial, we'll explain with simple examples how we can wrap texts using textwrap module using simple examples.

Example 1

As a part of our first example, we'll explain how we can wrap text using wrap() method of textwrapmodule.


  • wrap(text,width=70) - This method accepts a string and wraps it so that every line is at the most characters specified by width parameter. It'll list of strings where each entry represents a single line. It'll make sure that words are not broken. This method internally creates an instance of TextWrapper class which is responsible for wrapping text and calls wrap() method on it. The TextWrapper class has many parameters which can be passed to this method as well. We'll explain TextWrapper class in our upcoming examples.

We'll be using Zen of Python text (import this) for our examples. Our code for this example stores text in a variable named data. It then wraps text using wrap() method whose default width is 70 characters. We are then combining the list returned by the method using join() method of the string to create a single string out of it again.

import textwrap

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

wrapped_lines = textwrap.wrap(data)
print("Number of Lines : {}".format(len(wrapped_lines)))

print("\n".join(wrapped_lines))
Number of Lines : 13
The Zen of Python, by Tim Peters. Beautiful is better than ugly.
Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!

Example 2

As a part of our second example, we are again explaining the usage of wrap() method with different parameter settings.

Our code first calls wrap() method with a width of 40 characters and prints the result after combining a list of strings. It then again calls wrap() with a width of 40 characters, max line of 12, and a placeholder for extra lines as string [..Continued]. This will wrap the text with a width of 40 characters per line and will make sure that the output has a maximum of 12 lines. If total lines cross 12 lines then it'll omit lines beyond 12 lines and append [..Continued] string at the end of the 12th line.

import textwrap

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

wrapped_lines = textwrap.wrap(data, width=40)
print("Number of Lines : {}\n".format(len(wrapped_lines)))

print("\n".join(wrapped_lines))


wrapped_lines = textwrap.wrap(data, width=40, max_lines=12, placeholder="  [..Continued]")
print("\nNumber of Lines : {}\n".format(len(wrapped_lines)))

print("\n".join(wrapped_lines))
Number of Lines : 23

The Zen of Python, by Tim Peters.
Beautiful is better than ugly. Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!

Number of Lines : 12

The Zen of Python, by Tim Peters.
Beautiful is better than ugly. Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the  [..Continued]

Example 3

As a part of our third example, we'll explain how we can wrap text using fill() method.


  • fill(text,width=70) - It works exactly like wrap() method with only difference that it returns single string combining each line instead of returning list of lines like wrap().

Our code for this example is exactly the same as our code for the previous example with the only change that we have used fill() method in this example instead of wrap().

import textwrap

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

wrapped_data = textwrap.fill(data)

print(wrapped_data)

wrapped_data = textwrap.fill(data, width=40)

print()
print(wrapped_data)

wrapped_data = textwrap.fill(data, width=40, max_lines=12, placeholder="  [..Continued]")

print()
print(wrapped_data)
The Zen of Python, by Tim Peters. Beautiful is better than ugly.
Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!

The Zen of Python, by Tim Peters.
Beautiful is better than ugly. Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!

The Zen of Python, by Tim Peters.
Beautiful is better than ugly. Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the  [..Continued]

Example 4

As a part of our fourth example, we'll explain how we can shorten the string using shorten() method.


  • shorten(text, width) - It accepts string and width as input and wraps string so that the maximum number of characters is as specified by the width parameter. It makes sure that words are not broken. It also internally used TextWrapper instance hence accepts arguments accepted by TextWrapper class.

Our code for this example calls shorten() method with different width sizes and prints the final shortened string.

import textwrap

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

wrapped_data = textwrap.shorten(data, width=20)

print("Length of Wrapped Data : {}".format(len(wrapped_data)))
print(wrapped_data)

wrapped_data = textwrap.shorten(data, width=25)

print("\nLength of Wrapped Data : {}".format(len(wrapped_data)))
print(wrapped_data)

wrapped_data = textwrap.shorten(data, width=10)

print("\nLength of Wrapped Data : {}".format(len(wrapped_data)))
print(wrapped_data)

wrapped_data = textwrap.shorten(data, width=50, placeholder="  [...Continued]")

print("\nLength of Wrapped Data : {}".format(len(wrapped_data)))
print(wrapped_data)
Length of Wrapped Data : 16
The Zen of [...]

Length of Wrapped Data : 24
The Zen of Python, [...]

Length of Wrapped Data : 9
The [...]

Length of Wrapped Data : 49
The Zen of Python, by Tim Peters.  [...Continued]

Example 5

As a part of our fifth example, we'll explain how we can remove common leading white spaces in the text which is spread across multiple lines using dedent() method.


  • dedent(text) - This method accepts a string and removed common leading white spaces from it.

import textwrap

data = '''
    Hello All,
        
    How are you?
        
    Regards,
    CoderzColumn
'''

dedented_data = textwrap.dedent(data)

print(dedented_data)
Hello All,

How are you?

Regards,
CoderzColumn

Example 6

As a part of our sixth example, we'll explain how we can add prefix string to the selected lines of text where the text is spread across multiple using indent() method.


  • indent(text, prefix,predicate=None) - This method accepts text which is spread across multiple lines and adds string specified by prefix parameter at the beginning of each line. The predicate parameter accepts a function that takes as input single line and returns True if prefix needs to be added to it else False.

Our code for this example explains the usage of indent() with different parameter settings. It also explains how we can set the value for predicate parameter.

import textwrap

data = '''
Hello All,

How are you?

Regards,
CoderzColumn
'''

indented_data = textwrap.indent(data, "+\t")

print(indented_data)

indented_data = textwrap.indent(data, "+\t", lambda line : True)

print(indented_data)

indented_data = textwrap.indent(data, "+\t", lambda line : line.startswith("H"))

print(indented_data)
+	Hello All,

+	How are you?

+	Regards,
+	CoderzColumn

+
+	Hello All,
+
+	How are you?
+
+	Regards,
+	CoderzColumn


+	Hello All,

+	How are you?

Regards,
CoderzColumn

Example 7

As a part of our seventh example, we'll explain how we can create an instance of TextWrapper and use it to wrap texts.


  • TextWrapper() - This constructor creates an instance of TextWrapper which can be used to wrap text. Below is a list of parameters of the constructor.
    • width - It accepts a number specifying the maximum width of the line in character.
    • expand_tabs - It accepts a boolean value. If set to True will expands tabs into a list of spaces.
    • tabsize - It accepts a number specifying the number of spaces that will be used for one tab.
    • replace_whitespace - This parameter accepts boolean value. If it's set to True then it'll replace the white space character with a single space.
    • drop_whitespace - This parameter accepts boolean value. If set to True then white spaces at the beginning and end of the line will be removed.
    • initial_indent - This parameter accepts a string that will be prepended to the first line of the output.
    • subsequent_indent - This parameter accepts a string that will be prepended to all lines of output except first.
    • fix_sentence_endings - This parameter accepts boolean value. If set to True then TextWrapper tries to detect sentence endings and makes sure that sentences are separated by 2 white spaces.
    • break_long_words - This parameter accepts boolean value. If set to True then words which are longer than width parameter will broken.
    • break_on_hyphens - This parameter accepts boolean value. If set to True then wrapping will happen based on hyphens as well.
    • max_lines - It accepts a number specifying a maximum number of lines to keep in returned text. It'll drop all lines beyond that many numbers of lines.
    • placeholder - It accepts a string which will be appended to the end of the last line of text if the text has more line than a number of lines specified by max_lines parameters.

Important Methods of TextWrapper Instance

  • wrap(text) - This method works exactly like wrap() method introduced earlier but based on parameters setting of TextWrapper instance.
  • fill(text) - This method works exactly like wrap() method introduced earlier but based on parameters setting of TextWrapper instance.

Our code for this example starts by creating an instance of TextWrapper. It then prints the value of all attributes of the instance. It then calls wrap() and fill() methods on instance to explain their usage.

import textwrap

wrapper = textwrap.TextWrapper()

print("{:20s} - {}".format("width", wrapper.width))
print("{:20s} - {}".format("expand_tabs", wrapper.expand_tabs))
print("{:20s} - {}".format("tabsize", wrapper.tabsize))
print("{:20s} - {}".format("replace_whitespace", wrapper.replace_whitespace))
print("{:20s} - {}".format("drop_whitespace", wrapper.drop_whitespace))
print("{:20s} - {}".format("initial_indent", wrapper.initial_indent))
print("{:20s} - {}".format("subsequent_indent", wrapper.subsequent_indent))
print("{:20s} - {}".format("fix_sentence_endings", wrapper.fix_sentence_endings))
print("{:20s} - {}".format("break_long_words", wrapper.break_long_words))
print("{:20s} - {}".format("break_on_hyphens", wrapper.break_on_hyphens))
print("{:20s} - {}".format("max_lines", wrapper.max_lines))
print("{:20s} - {}".format("placeholder", wrapper.placeholder))

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

wrapped_lines = wrapper.wrap(data)
print("Number of Lines : {}".format(len(wrapped_lines)))
print()
print("\n".join(wrapped_lines))

print()

print(wrapper.fill(data))
width                - 70
expand_tabs          - True
tabsize              - 8
replace_whitespace   - True
drop_whitespace      - True
initial_indent       -
subsequent_indent    -
fix_sentence_endings - False
break_long_words     - True
break_on_hyphens     - True
max_lines            - None
placeholder          -  [...]
Number of Lines : 13

The Zen of Python, by Tim Peters. Beautiful is better than ugly.
Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!

The Zen of Python, by Tim Peters. Beautiful is better than ugly.
Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!

Example 8

As a part of our eighth example, we are demonstrating how we can set different values of parameters of TextWrapper instance. We are then also wrapping data using this instance to show the impact of the parameters on the wrapped text.

import textwrap

wrapper = textwrap.TextWrapper(width=40,
                               tabsize=4,
                               fix_sentence_endings=True,
                               break_long_words=False,
                               break_on_hyphens=False,
                               max_lines=10)

print("{:20s} - {}".format("width", wrapper.width))
print("{:20s} - {}".format("expand_tabs", wrapper.expand_tabs))
print("{:20s} - {}".format("tabsize", wrapper.tabsize))
print("{:20s} - {}".format("replace_whitespace", wrapper.replace_whitespace))
print("{:20s} - {}".format("drop_whitespace", wrapper.drop_whitespace))
print("{:20s} - {}".format("initial_indent", wrapper.initial_indent))
print("{:20s} - {}".format("subsequent_indent", wrapper.subsequent_indent))
print("{:20s} - {}".format("fix_sentence_endings", wrapper.fix_sentence_endings))
print("{:20s} - {}".format("break_long_words", wrapper.break_long_words))
print("{:20s} - {}".format("break_on_hyphens", wrapper.break_on_hyphens))
print("{:20s} - {}".format("max_lines", wrapper.max_lines))
print("{:20s} - {}".format("placeholder", wrapper.placeholder))

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

print()
print(wrapper.fill(data))
width                - 40
expand_tabs          - True
tabsize              - 4
replace_whitespace   - True
drop_whitespace      - True
initial_indent       -
subsequent_indent    -
fix_sentence_endings - True
break_long_words     - False
break_on_hyphens     - False
max_lines            - 10
placeholder          -  [...]

The Zen of Python, by Tim Peters.
Beautiful is better than ugly.  Explicit
is better than implicit.  Simple is
better than complex.  Complex is better
than complicated.  Flat is better than
nested.  Sparse is better than dense.
Readability counts.  Special cases
aren't special enough to break the
rules.  Although practicality beats
purity.  Errors should never pass [...]

Example 9

As a part of our ninth example, we are again demonstrating how we can set different values of parameters of TextWrapper instance. We are then also wrapping data using this instance to show the impact of the parameters on the wrapped text.

import textwrap

wrapper = textwrap.TextWrapper(width=40,
                               tabsize=4,
                               fix_sentence_endings=True,
                               break_long_words=False,
                               break_on_hyphens=False,
                               max_lines=12,
                               placeholder="  [..Continued]")

print("{:20s} - {}".format("width", wrapper.width))
print("{:20s} - {}".format("expand_tabs", wrapper.expand_tabs))
print("{:20s} - {}".format("tabsize", wrapper.tabsize))
print("{:20s} - {}".format("replace_whitespace", wrapper.replace_whitespace))
print("{:20s} - {}".format("drop_whitespace", wrapper.drop_whitespace))
print("{:20s} - {}".format("initial_indent", wrapper.initial_indent))
print("{:20s} - {}".format("subsequent_indent", wrapper.subsequent_indent))
print("{:20s} - {}".format("fix_sentence_endings", wrapper.fix_sentence_endings))
print("{:20s} - {}".format("break_long_words", wrapper.break_long_words))
print("{:20s} - {}".format("break_on_hyphens", wrapper.break_on_hyphens))
print("{:20s} - {}".format("max_lines", wrapper.max_lines))
print("{:20s} - {}".format("placeholder", wrapper.placeholder))

data = "The Zen of Python, by Tim Peters. Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"

print()
print(wrapper.fill(data))
width                - 40
expand_tabs          - True
tabsize              - 4
replace_whitespace   - True
drop_whitespace      - True
initial_indent       -
subsequent_indent    -
fix_sentence_endings - True
break_long_words     - False
break_on_hyphens     - False
max_lines            - 12
placeholder          -   [..Continued]

The Zen of Python, by Tim Peters.
Beautiful is better than ugly.  Explicit
is better than implicit.  Simple is
better than complex.  Complex is better
than complicated.  Flat is better than
nested.  Sparse is better than dense.
Readability counts.  Special cases
aren't special enough to break the
rules.  Although practicality beats
purity.  Errors should never pass
silently.  Unless explicitly silenced.
In the face of ambiguity,  [..Continued]

This ends our small tutorial explaining how we can wrap long text properly using textwrap module of Python. Please feel free to let us know your views in the comments section.

Sunny Solanki  Sunny Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription