'How to Format Jupyter notebook in VSCode?

We can format python code in the jupyter notebook in the browser. After I change to VSCode and use the Microsoft extension, I find I can not format Jupyter notebook any more. Does anyone know how to solve this?



Solution 1:[1]

As Kyle Carow stated in their answer to Ian Huff: Formatting of notebooks is available by now.

  • MacOS: Option+Shift+F
  • Windows: Ctrl+Shift+I (This is cited from Kyle Carow as I didn't test this myself yet.)

Pressing these keys will either trigger a formatting of the active cell or the notebook as a whole if no cell is active.

Solution 2:[2]

Windows: Shift+Alt+F

Is what worked for me with Black formatter set up on VS Code Version: 1.64.2

Or right click "Format Notebook" to format entire notebook.

Format Notebook

Solution 3:[3]

I do not think VS Code support formatting of code cells, but if you use the black code formatter, then you can use the blackcellmagic %%black to format the code in a cell.

You need to have pip install black and blackcellmagic, details here: https://github.com/csurfer/blackcellmagic

Solution 4:[4]

I'm not exactly sure what is being asked here. But currently in VS Code the notebook editor and interactive window do not support formatting python code.

However we are moving to a new UI for those features which will support all the formatting features of VS Code in .py files. If you try out VS Code - Insiders now you should see this support and can try it out. This new UI will eventually be rolling out to VS Code stable.

Edit: The new UI which supports formatting in cells is now out by default for stable users.

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 Nico
Solution 2 Syscall
Solution 3 PerJensen
Solution 4