How to Reformat Text to a Specified Number of Columns in Python



Python


In this article, we show how to reformat text to a specified number of columns in Python using the textwrap module.

So let's say that we have a block of text that goes a certain horizontal length across your screen. You may want to reformat this text so that it takes up less horizontal space across the screen. You can reformat this block of text using the textwrap module.

With the textwrap module, you can specify the number of columns that you want the text to appear across.

If you know HTML, this is just like the textarea element. With the textarea element, you specify the number of columns (and/or rows) that you want the element to be.

The Python textwrap module can allow us, just like the HTML textarea element, to determine how much width a block of text takes up.

The textwrap module has a fill() function that allows us to specify as the first parameter the text that we want to reformat and as a second parameter the number of columns that you want this text to span.

This is useful when you want a block of text to only take up a certain amount of horizontal space across the screen.

To see how this works, look at the following code below.



So let's now go over the code.

So the first thing we must do is import the textwrap module.

Once this is done, we create our text and assign it to a variable, in this case, text1.

Once this is done, we use the print() function in combination with the fill() function of the textwrap module to determine how many columns the text should span horizontally on the screen.

We first start out with column value of 70.

We then go to a column valiue of 60.

We then go to a column value of 40.

You see how the horizontal space gets truncated each time.

The textwrap module is useful in times when you want text to appear within a predetermined space on your screen.

And this is how we can reformat text to a specified number of columns in Python using the textwrap module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...