Justifying text in a terminal with Python

Have you ever wanted to print text in your terminal to the utmost left while having another text on the same line to the utmost right ?

I bet you once did, and the sought result should look something like this :

A lot of threads out there in the net suggest using extra libraries like curses  and so on, but in this tutorial, we’re gonna use only standard and built-in Python functions.

Printing text to the left is obvious, but to print text to the right, we must know the terminal’s width. In Python, we can make use of the os lib to get that done :

Rows is the numbers of horizontal lines, and columns is the width of the terminal in lines. Just keep in mind that the read()  method returns string objects.

Now that we know the width of our terminal, let me introduce the rjust()  and ljust()  string methods. rjust() , like right justified, returns the right justified string it’s been called on. In other words, if I print "myText".rjust(4)  I will see on my screen ”    myText” (That’s my string padded with 4 spaces on the left). And yes, that’s right, ljust()  is the same but for left justified text. If you wanna justify with something other than spaces, you can pass your padding character to the function just like this :

which will print “myText####”.

Now that we’ve got all the elements we need, the rest is pretty straight-forward :

So we just append the left string with int(columns) - len(right) spaces in order to leave just enough space for the text to be printed on the right.

The same result can be achieved with rjust() :

That’s it for this tutorial. Just remember to update your columns whenever you are going to print justified text, you know, users can sometimes be nasty and may like changing their terminal size very often 😉

P.S: I haven’t tested, but this may create some discrepancies with some weird fonts. Make sure to use a monospace font !