01. Center Content in Python using the os module.

Hi there!

This is going to be the first of (hopefully) many small tips that I would like to share with the community that has helped me so much throughout my years of coding!

As the title states, I will be showing you how to format content in Python such that it gets centered to your terminal window perfectly.

Python has several built-in modules, one of which is the os module. It allows users to perform commands pertaining to the Operating System.

We will be looking at the get_terminal_size method from the os module.

As the name suggests, the function allows users to get the terminal size of the terminal in which python is being run.

These commands work in the IDLE as well as in normal shells

The function returns a tuple of values. The first value is the number of columns of the terminal and the second value is the number of rows of the terminal.

Here is the code:

Let us go line by line:

import os

Here , we import the os module for usage.

terminal_size = os.get_terminal_size().

In this, we assign the return value of the function to a variable called terminal_size. This makes it easy for us to access it later. *

print("Hello there!".center(terminal_size.columns))

This is the line that most of you will be here for. Strings in Python have some methods that can be applied to them. One such method is .center().

The center() method will align the string using a specified character (default is space) as the fill character.

Syntax:

string.center(length, character)

Here, length is a required argument while character is an optional argument.

Length is the final length of the string that will be printed.

When we pass the number of columns of the terminal as the length, the method automatically centers our content as we are asking it to cover the whole terminal.

Final Ouput:

image.png

(Font used: JetBrains Mono, Terminal Used: Ubuntu 20.04 on WSL)

A Problem you may face and it's solution:

When we assign the return value of the get_terminal_size() command to a variable like terminal_size, we are essentially locking the value that we wish to choose.

If the user decides to change the size of the terminal, it will cause either extra or too few fill characters to appear.

To fix this, we can call the function every time we need it.

This would refresh the value and provide us with the correct one. An example to demonstrate this:

Output:

image.png

image.png

That is it for now! Hope to see you next time!