How to wrap code/text in Jupyter notebooks
PythonJupyter NotebookPython Problem Overview
Python Solutions
Solution 1 - Python
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.
Solution 2 - Python
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 - Python
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 - Python
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 '''
Solution 5 - Python
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:
- hit
F1
- choose Preferences: Open Settings (UI)
- start typing in wrap
- 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.
Solution 6 - Python
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.