How to use vim to solve python code indentation inconsistency, error: IndentationError: unindent does not match any outer indent

Table of contents

1 reason

Python code requires strict indentation. Unlike other languages, curly braces {} or keywords begin, end, etc. are used to identify code blocks.Python uses indentation to distinguish code blocks, so indentation is part of the grammar in python, and consistent indentation must be ensured, if the indentation method is inconsistent, it will cause an error when the code runs.

As for the indentation method used in python, we can use 2 spaces, 3 spaces, 4 spaces, a tab key, or a combination of spaces and tabs, etc. as the indentation method.But you must ensure that the indentation used for each line is consistent, if there is an inconsistency, there will be an IndentationError: unindent does not match any outer indent problem.

2 solutions

  • Open the python code with vim, and then set:setlocal list, to display all the tab keys in the code script, but the output format has a $ symbol at the end of each line, which is not conducive to viewing. By setting:set listchars=tab:>~, trail:.
  • If you find that some codes have tab keys and some do not, you need to convert the tab key to a space when writing python code in the current script, and set it in vimset expandtab, the existing tab key needs to be manually changed, and there is no problem when setting the new code, and then using the tab key to indent.

Guess you like

Origin blog.csdn.net/BGoodHabit/article/details/125747828