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.
As a part of our first example, we'll explain how we can wrap text using wrap() method of textwrapmodule.
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))
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))
As a part of our third example, we'll explain how we can wrap text using fill() method.
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)
As a part of our fourth example, we'll explain how we can shorten the string using shorten() method.
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)
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.
import textwrap
data = '''
Hello All,
How are you?
Regards,
CoderzColumn
'''
dedented_data = textwrap.dedent(data)
print(dedented_data)
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.
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)
As a part of our seventh example, we'll explain how we can create an instance of TextWrapper and use it to wrap texts.
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))
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))
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))
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.
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
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.
If you want to