在 VS Code 和 PyCharm 中,可以設定自動轉換縮排,以避免 Tab 和空格混用導致的 IndentationError。以下是詳細設定方式:
VS Code 設定自動轉換縮排
VS Code 預設使用 空格 (spaces) 而非 Tab,但可以手動調整設定,以確保統一縮排方式。
方法 1:透過設定介面調整
- 打開 VS Code。
- 進入「設定」 (可按
Ctrl + ,或Cmd + ,(Mac))。 - 搜尋 "insert spaces"。
- 確保 Editor: Insert Spaces 已啟用(這會將 Tab 轉換為空格)。
- 搜尋 "tab size" 並設定為 4 (建議 Python 使用 4 個空格)。
- 搜尋 "trim trailing whitespace",確保這個選項已啟用,以避免多餘的空格影響程式碼。
- 關閉設定頁面,設定會自動儲存。
方法 2:手動修改 settings.json
- 開啟
settings.json(按Ctrl+Shift+P,輸入Preferences: Open Settings (JSON))。 - 加入以下設定:
{ "editor.insertSpaces": true, "editor.tabSize": 4, "editor.detectIndentation": false, "files.trimTrailingWhitespace": true } - 儲存並關閉。
方法 3:在每個專案中指定縮排
若希望每個專案的設定不同,可建立 .editorconfig 檔案:
- 在 專案根目錄 新增
.editorconfig檔案。 - 添加以下內容:
[*.py] indent_style = space indent_size = 4 trim_trailing_whitespace = true - 儲存並關閉。
PyCharm 設定自動轉換縮排
PyCharm 預設使用 空格 (spaces) 來縮排,但你可以確認或調整設定。
方法 1:透過「設定」介面調整
- 打開 PyCharm。
- 進入 File → Settings (
Ctrl + Alt + S),或 PyCharm → Preferences (Cmd + ,on Mac)。 - 展開 Editor → Code Style → Python。
- 確保:
- "Use tab character" 未勾選(這樣會使用空格)。
- "Tab size" 設為 4。
- "Indent" 設為 4。
- 點擊 Apply,然後 OK。
方法 2:讓 PyCharm 自動轉換 Tab 為空格
- 進入 Settings (
Ctrl + Alt + S)。 - 搜尋 "Convert Indents"。
- 選擇 Convert Indents → To Spaces。
方法 3:在 .editorconfig 設定全專案的縮排規則
如果你希望整個專案統一規則,可以:
- 在專案根目錄 建立
.editorconfig檔案。 - 加入:
[*.py] indent_style = space indent_size = 4 trim_trailing_whitespace = true - 儲存並關閉。
這樣設定之後,無論在 VS Code 還是 PyCharm,都可以避免 Tab 和空格混用造成的 IndentationError!
沒有留言:
張貼留言