When using Ctrl + / to comment out code blocks in Jupyter Notebook, the comment character may appear at the beginning of the line by default, making the indentation look messy. This issue is discussed in the related Jupyter Notebook thread:
https://github.com/jupyter/notebook/issues/954
One workable solution is to install and enable the comment-uncomment extension from jupyter_contrib_nbextensions.
conda update notebook
conda install jupyter notebook
conda install -c conda-forge jupyter_contrib_nbextensions
conda install -c conda-forge jupyter_nbextensions_configurator
jupyter contrib nbextension install --user
jupyter nbextension enable comment-uncomment/main
After enabling it, when you use Ctrl + / to comment code again, the comment character will follow the original indentation more cleanly. For example:
# This program prints Hello, world!
print('Hello, world!')
On macOS, you may encounter the following error:
[jupyter_nbextensions_configurator] error loading comment-uncomment/main
If the extension fails to load after being installed with conda, you can install these two packages with pip instead:
conda update notebook
conda install jupyter notebook
pip install jupyter_contrib_nbextensions jupyter_nbextensions_configurator
jupyter contrib nbextension install --user
jupyter nbextension enable comment-uncomment/main
After installation, restart Jupyter Notebook and reopen the Notebook page in your browser. If it still does not take effect, check whether the extension has been enabled:
jupyter nbextension list
If you are using a newer version of JupyterLab, this nbextension approach may not apply. First confirm whether you are running classic Notebook, Notebook 7, or JupyterLab, then handle extensions according to the mechanism supported by your current environment.
