| title | description | author | ms.author | ms.subservice | ms.topic | ms.date | manager |
|---|---|---|---|---|---|---|---|
Reformat your python code in Visual Studio |
Automatically format your Python code in Visual Studio, including the code spacing, statements, long line wrapping, and code comments. |
cwebster-99 |
cowebster |
python |
conceptual |
01/25/2024 |
jmartens |
Visual Studio lets you quickly reformat code to match specific formatter standards. In this article, you explore how to access and enable formatting features.
You can set your source code formatter through Tools > Options > Text Editor > Python > Formatting. Python Tools in Visual Studio support source code formatting with autopep8, Black formatter, and yapf.
:::image type="content" source="media/options-editor-formatting.png" alt-text="Screenshot of the Python formatting options in Visual Studio and the Black formatter option selected." lightbox="media/options-editor-formatting.png":::
Python support in Visual Studio also adds the Fill Comment Paragraph command to the Edit > Advanced menu as described in a later section.
You can apply formatting settings to all content in a file or only to a specific selection.
To format a selection, use one of the following methods:
- Select Edit > Advanced > Format Selection.
- Select the keyboard shortcut Ctrl+E+F.
To format the whole file, use one of the following methods:
- Select Edit > Advanced > Format Document.
- Select the keyboard shortcut Ctrl+E+D.
You can enable word wrapping in Tools > Options > Text Editor > Python > General. In the Settings section, select the Word wrap checkbox.
:::image type="content" source="media/word-wrap-setting.png" alt-text="Screenshot that shows how to enable word wrapping for Python in Visual Studio." lightbox="media/word-wrap-setting.png":::
The Edit > Advanced > Fill Comment Paragraph option reflows and formats comment text. You can also access the feature by using the keyboard shortcut Ctrl+E+P.
Use the feature to break up long lines of text, as shown in this example:
# This is a very long long long long long long long long long long long long long long long long long long long commentThe text is reformatted as multiple lines:
# This is a very long long long long long long long long long long long long
# long long long long long long long commentUse the feature to combine short lines of text, as shown in this example:
# Short line of text
# more text
# textThe text is reformatted into a single line:
# Short line of text more text text