First install the yapf library:
pip install yapf
Then open File—Preferences—Settings in the VS Code menu bar, search for "python.formatting.provider" in the search box, and then select "yapf" in the drop-down menu, as shown in the figure below: When using, just
select The Python code that needs to be formatted, then right-click and select "Format Selection" to achieve automatic formatting.