'How to wrap code/text in Jupyter notebooks

I am using jupyter-notebooks for python coding. Is there a way to wrap text/code in a jupyter notebook code cell?

Picture provided below.

Text not wrapping

By wrap text means "how text is wrapped in MS-word"



Solution 1:[1]

Find your configuration directory via jupyter --config-dir (mine is ~/.jupyter). Then edit or create nbconfig/notebook.json to add the following:

{
  "MarkdownCell": {
    "cm_config": {
      "lineWrapping": true
    }
  },
  "CodeCell": {
    "cm_config": {
      "lineWrapping": true
    }
  }
}

(If you have something else in it, ensure you have valid JSON with no trailing commas after }s.)

Restart Jupyter and reload your notebook.

Source: https://github.com/jupyter/notebook/issues/106

Solution 2:[2]

In addition to Dan's answer, you can apply line wrapping for all cells (code or markdown) by specifying the top object as Cell. Adding the code below to your ~/.jupyter/nbconfig/notebook.json

{
  "Cell": {
    "cm_config": {
      "lineWrapping": true
    }
  }
}

Ex: This is my cell config

{
  "Cell": {
    "cm_config": {
      "lineNumbers": false,
      "lineWrapping": true
    }
  }
}

Solution 3:[3]

Easiest for me was this, straightforward and does not require a pip install:

from textwrap import wrap
long_str = 'I rip wrap unravel when I time travel, with beats in my head'
lines = wrap(long_str, 20) #wrap outputs a list of lines
print('\n'.join(lines))    #so join 'em with newline

#prints: 
#I rip wrap unravel
#when I time travel,
#with beats in my
#head

Solution 4:[4]

This may not be as satisfactory of an answer but while working Google Colab, I use the three single quote marks above and below the line of comments. Once quote marks are in place, I can hit return where I see fit.

Original comment:

# Using the number of rows from the original concatenated dataframe and the trimmed dataframe, quantify the percent difference between the number of rows lost

Solution:

''' Using the number of rows from the original concatenated dataframe and the trimmed dataframe, quantify the percent difference between the number of rows lost '''

Here is a screen grab of the solution: enter image description here

Solution 5:[5]

I am working with Jupyter notebook (.ipynb) through VSC Visual Studio Code, and I did find out that setting line/word wrapping could be set as follows:

  1. hit F1
  2. choose Preferences: Open Settings (UI)
  3. start typing in wrap
  4. Editor: Word Wrap Controls how lines should wrap pops up, change to On

It works for code (Python cells). Markdown cells work fine even without changing above setting.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan
Solution 2 eden
Solution 3
Solution 4 Moyo Ajayi
Solution 5 heniczyna