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.
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:
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.str.wrap()
method acts on one string column and takes one argument width
specifying the target line width.str.wrap()
: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
.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.
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.