Wrapping

We wish to format a string as a paragraph with a certain line width. In other words, we wish to insert a newline character at a given line width (in number of characters). This is often useful for display purposes e.g. in notebooks or web apps.

df_2 = df.assign(
    col_2 = df['col_1'].str.wrap(width=10)
)

Here is how this works:

  • We use the str.wrap() method from the str accessor set of string manipulation methods of Pandas Series to wrap the values in the column col_1 into a paragraph where each line has a maximum width of 10 characters.
  • 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.
PYTHON
I/O