Formatting A Text Based On Number Of Columns In Python

Say you have a text which is very long and occupies many columns or, in other words, say you have a text which is so long that the end user is seeing a scrollbar because of the limited screen size.

Now, when the text is very long and the user viewable area is limited, then as a programmer we have to do some adjustments to pull down some of the text to the next line.

Well, it feels daunting, but it is very easy to achieve this in Python.

Problem Statement

How to re-format a long text so that it can fit into the user-provided number of columns?

Solution

Like every other Python application, here we need to import the required module and that is textwrap:

import textwrap

Setting Number Of Columns

Once package is imported, we need to call function fill(…) as shown below:

text = “Welcome to Medium! I hope you are enjoying reading and writing articles on this platform.”
print(textwrap.fill(text,40))

On running the above two lines of code, you can see that output is formatted as shown below with the column value as 40:

Formatting A Text Based On Number Of Columns In Python

Setting Initial Indentation

If you want to set the indentation for your very first line, it can be done as shown below:

textwrap.fill(text,40, initial_indent='      ')

The above code will produce the output as shown below:

Formatting A Text Based On Number Of Columns In Python

Setting Subsequent Indentation

If you want to set the indentation for your very line after first line, it can be done as shown below:

textwrap.fill(text,40, subsequent_indent='      ')

The above code will produce the output as shown below:

Formatting A Text Based On Number Of Columns In Python

Hope you find this module handy and super easy to use. You can use this to adjust output based on your terminal size :)

Do not forget to watch the hands-on recording of this article on my YouTube channel.


Similar Articles