Alignment

We wish to align text to the left, right, or center within a given width specified as a number of characters.

Note that if the length of the string is larger than the specified line width, the original string is returned as is.

Left Align

We wish to align text to the left of each line with empty spaces added to the right to fill the desired line width.

In this example, we wish to align the values of the string column col_1 to the left while setting the line width to 25.

df_2 = df.assign(
    col_2 = df['col_1'].str.ljust(25)
)

Here is how this works:

  • We use the str.ljust() method from the str accessor set of string manipulation methods of Pandas Series to left align the values of the string column col_1 in a line of width 25.
  • The str.wrap() method acts on one string column and takes one argument width specifying the target line width.
  • Two points to note about wrapping via str.wrap():
    • New lines are inserted only between words.
    • If a word is longer than the width, new line characters \n will be inserted inside the word breaking it over multiple lines. Therefore, the output will always be within the specified line width.
  • The output data frame df_2 will have the same number of rows as the original data frame df but with an additional columncol_2 holding the wrapped version of the column col_1.

Right Align

We wish to align text to the right of each line with empty spaces added to the left to fill the desired line width.

In this example, we wish to align the values of the string column col_1 to the right while setting the line width to 25.

df_2 = df.assign(
    col_2 = df['col_1'].str.rjust(25)
)

Here is how this works:

This works similarly to the Left Align case above except that we use the str.rjust() method because we wish to right align.

Center Align

We wish to align text to the center of each line with roughly an equal number of empty spaces added to the left and right to fill the desired line width.

In this example, we wish to align the values of the string column col_1 to the center while setting the line width to 25.

df_2 = df.assign(
    col_2 = df['col_1'].str.center(25)
)

Here is how this works:

This works similarly to the Left Align case above except that we use the str.center() method because we wish to center align.

PYTHON
I/O