Python String Padding

Chapter 16 8 mins

Learning outcomes:

  1. What is string paddding
  2. Left-alignment using ljust()
  3. Right-alignment using rjust()
  4. Center-alignment using center()

Introduction

In the early days of computers, we did not have the sophisticated graphics that we have today. Computer programs, operating systems, were largely limited to the shell snippets we work with today only occassionally.

With time, since program output was mainly confined to the terminal, it meant that being able to effectively work with strings was necessary. Tables, formatted data, everything was somehow required to be displayed.

With this increasing need, many string utilities sprung up. One of them, which is useful to date, is string padding.

In this chapter, we shall understand what is padding and how to use it to format given strings as they are output in Python giving them a neat and clean look.

What is string padding?

In simple terms:

String padding is to extend a string to a given length with a given fill character.

For example, given the string 'Hello', padding it to a length of 10 with the fill character - would give the string 'Hello-----'.

String padding is extremely useful when we have to display data in the format of a table in the shell.

The data of each column is padded to some length. This makes data of the next column aligned with one another. Altogether, the data seems to be nicely grouped and equally spaced with the help of string padding.

Now padding is essentially stretching a string to a certain length with a given fill character. But this doesn't say anything about where the fill character goes.

For instance, given the string 'A' and fill character -, there a handful of ways to pad this string to the length of 5:

  1. Put all the required - characters at the start of 'A', i.e. '----A'.
  2. Put all the required - characters at the end of 'A', i.e. 'A----'.
  3. Put all the required - characters in such a way as to centralize 'A' between them, i.e. '--A--'.

These are the three ways to pad a string with a given fill character in almost all languages that provide string padding utilities out of the box.

In Python, we have three methods at our dispense to pad a string in one of these three ways, using any fill character we wish to use.

Let's see them one-by-one...

Left align — ljust()

The first method we'll be seeing is ljust().

The string method ljust() pads a string to a given length with a fill character by putting the character at the end of the string.

This makes the actual string look left-aligned.

What does the name 'ljust' mean?

The name 'ljust' stands for 'left-justified'. Left justified, or left aligned, means that the text has a common left margin.

Here's the syntax of ljust():

string.ljust(length[, fill])

length is the length of the final padded string, and fill is the character to pad string with. As can be seen, fill is optional; if omitted, it defaults to ' ' — the space character.

Let's consider an example using ljust():

print('Hello.'.ljust(20) + '|')
print('How are you?'.ljust(20) + '|')
Hello. | How are you? |

Here we call ljust() without a fill character; hence it goes with its default fill character, i.e. ' '. The way we are able to visualize the padding is by the | character that's output after the starting strings.

Remember one thing: supposing that the string you're trying to pad has a length n and the length to which you wish to pad it is m, if m is less than n, i.e. the length of the padded string is less than that of the actual string; nothing would be added and the string would be returned as it is.

Below shown is an example:

print('Hello World!'.ljust(3) + '|')
Hello World!|

This clearly shows that padding is meaningful only when it has to be done to a length greater than the length of the actual string.

Right align — rjust()

The opposite of ljust() is rjust().

It pads a string to a given length with a fill character by putting the character at the start of the string.

This makes the actual string look right-aligned.

What does the name 'rjust' mean?

The name 'rjust' stands for 'right-justified'. Right justified, or right aligned, means that the text has a common right margin.

Syntactically, rjust() is identical to ljust():

string.rjust(length[, fill])

length is the length of the final padded string, and fill is the character to pad string with. If omitted, fill defaults to ' ' — the space character.

As before, time to consider some examples:

print('Hello.'.rjust(20))
print('How are you?'.rjust(20))
Hello. How are you?

See how both the lines printed here are right aligned with one another — this is because they have the same padding length 20. Had we passed a differing length to both these rjust() calls, we wouldn't have achieved this neat look.

When creating table columns, usually the padding length is kept the same.

Let's use some other fill character:

print('Hello.'.rjust(20, '-'))
print('How are you?'.rjust(20, '-'))
--------------Hello. --------How are you?

Center aligned — center()

Where ljust() pads a string making text left-aligned, rjust() pads a string making text right-aligned, the center() method sits in between them.

The center() method pads a string to a given length with a fill character by putting the character at both the ends of the string.

Visually this makes the actual string look centralised.

As with ljust() and rjust(), center() has the same syntax:

string.center(length[, fill])

length is the length of the final padded string, and fill is the character to pad string with. If omitted, fill defaults to ' ' — the space character.

Let's centralize a couple of string using center():

print('Hello.'.center(20))
print('How are you?'.center(20))
Hello. How are you?

As is apparent in the output, center() centralises a string between a given fill character. Here, since the padding length of both the center() calls is the same i.e. 20, both the string would look centered relative to one another.

Let's try this example with - as the fill character:

print('Hello.'.center(20, '-'))
print('How are you?'.center(20, '-'))
-------Hello.------- ----How are you?----

Same as before; just the spaces replaced with hyphens (-).

Uneven fill characters

When using center(), if the number of fill characters on either end of the actual string can't be the same, then the right side gets the larger number of characters.

For instance, consider the code below:

print('A'.center(6, '-'))
--A---

Here, 'A' has to be centered to a length of 6 between the - character. However, 'A' has a length of 1 which means that 5 - characters have to be put around 'A'. Since 5 can't be broken down into a half, the left side gets 2 - characters and the right side gets 3.