How to wrap code/text in Jupyter notebooks

Question:

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”

Asked By: Anuj Gupta

||

Answers:

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

Answered By: Dan

Shortest Answer Ever

Try adding a ‘ ‘ in between the lines of code you need to split.

This allows you to split your code over different lines and helps it look prettier.

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
    }
  }
}
Answered By: eden

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

Answered By: Moyo Ajayi

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.

Answered By: heniczyna

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
Answered By: The Real Dre

You can do:

Settings > Advanced setting Editor > TextEditor > checkbox enable Line Wrap.

Advanced settings editor

Answered By: Kumar Arrpit Singh

Since none of these solutions worked for me, I opted for a different approach and wrote a simple column-wrapping print function that you can use to manually guarantee that the lines of any string will remain in view, for simple output checking scenarios.

def printwr( item, wrapCol=70 ):
    """ wrap printing to column limit """
    posit = 0
    while True:
        # if remaining legnth eq/less than wrapCol, print and rturn
        if len(item[posit:]) <= wrapCol: print(item[posit:]); return
        # else take wrapCol chars from last index
        llim = posit+wrapCol+1
        # if more than one item, drop last contiguous non-space sequence (word)
        lineSpl = item[posit:llim].split(' ')
        segment = ' '.join(lineSpl[:-1]) if len(lineSpl)>1 else lineSpl
        # print segment and increment posit by length segment
        posit += len(segment)+1
        print(segment)

For example, for

exampleStr = "populations tend to cluster in the foothills and periphery of the rugged Hindu Kush range; smaller groups are found in many of the country's interior valleys; in general, the east is more densely settled, while the south is sparsely populated"

printwr(exampleStr) 

produces:

populations tend to cluster in the foothills and periphery of the
rugged Hindu Kush range; smaller groups are found in many of the
country’s interior valleys; in general, the east is more densely
settled, while the south is sparsely populated

Answered By: romstroller1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.