How to Indent a Paragraph in Python 


               


How to Indent a Paragraph in Python



Python


In this article, we show how to indent a paragraph in Python using the textwrap module.

The textwrap module is a standard module of Python, so you do not have to install it. It comes with Python.

Using the textwrap module, we can indent a paragraph any amount of spaces we desire using the initial_indent attribute and setting it equal to a string that contains the amount of spaces we want the first sentence of the paragraph indented by.

With the initial_indent attribute, only the first sentence of the paragraph gets indented, which is the typical indentation you see in writing.

So below we show the code that indents the first sentence of a paragraph in Python using the initial_indent attribute of the fill() function.



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. We specify the text that we want to include as the first parameter. As the second parameter, we specify the initial_indent attribute and set it equal to ' ' (4 spaces). So there is an indentation of 4 spaces in the paragraph.

Again, you can adjust this to any amount of spaces that you desire and it will work.

And this is how we can indent a paragraph 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...