How To Indent Print Text In Python

When working with text in Python, you may find yourself in situations where you want to align or format your text output to be more structured and easier to read.

This tutorial will guide you on how to indent print text in Python in order to achieve this. By indenting text, it simply means adding extra spaces or characters at the beginning of a line. The following steps will demonstrate various methods of indenting print text.

Step 1: Using String Concatenation

The simplest way to indent text in Python is by using string concatenation. This can be achieved by adding a string containing the desired number of spaces or characters before the text you want to print.

Output:

    This is indented text.

Step 2: Using String Multiplication

Another method is using string multiplication, which allows you to repeat a string a specified number of times. In this example, we will repeat the space character 4 times to create an indent.

Output:

    This is indented text.

Step 3: Using format() Function

The format() function is a powerful Python string formatting technique that allows you to create formatted strings with placeholders. In this case, we can use the format() function to create an indented string.

Output:

    This is indented text.

Step 4: Using f-strings (Python 3.6 and later)

F-strings, also known as format string literals, were introduced in Python 3.6 as an alternative to the format() function. They allow you to embed expressions inside string literals, making it easier to create formatted strings. You can use f-strings to create indented text in a similar way as the format() function.

Output:

    This is indented text.

Full Code:

Conclusion

In this tutorial, you’ve learned four different methods for indenting print text in Python. Each method has its own advantages and use cases, but generally, using the format() function or f-strings is recommended since they offer more flexibility when working with formatted strings. However, for simple cases, string concatenation or string multiplication might suffice.