PyCharm Code Editing

As a professional Python IDE, PyCharm provides powerful code editing features.

This chapter will detail the core features of code editing, including smart completion, shortcut operations, code refactoring, and other efficient development techniques.


Basic Editing Features

Code Completion

PyCharm provides multiple smart completion methods:

Completion Type Trigger Method Description
Basic Completion Ctrl + Space(Win/Linux)
⌘ + Space(Mac)
Displays suggestions for variables, functions, classes, etc.
Smart Type Completion Ctrl + Shift + Space Recommends more precise types based on context
File Name Completion Automatically triggered when entering a path Quickly completes file paths
Dynamic Template Completion Enter abbreviation (e.g.main + Tab) Quickly generate code snippets (e.g.if __name__ ==...)

Enterim + Tab→ Auto-completes toimport:

Enterfor + Tab→ Generate completeforloop structure:


Syntax Highlighting

PyCharm automatically colors code elements:

  • Keywords(def, class): blue

  • Strings: green

  • Comments: gray

  • Error syntax: red wavy underline

Custom Highlighting:

  1. 设置 → 编辑器 → 配色方案(Color Scheme)

  2. Adjust the colors of Python syntax elements


Code Folding

Action Shortcut (Win/Linux) Shortcut (Mac)
Collapse current code block Ctrl + - ⌘ + -
Expand current code block Ctrl + + ⌘ + +
Collapse all code blocks Ctrl + Shift + - ⌘ + Shift + -
Expand all code blocks Ctrl + Shift + + ⌘ + Shift + +

Move the mouse to the left of the code area in the editor to see a downward arrow; clicking it can also collapse:

Code structures that support folding:

  • Functions/Methods

  • Class definitions

  • Multi-line comments

  • Import statement groups


Shortcuts and Efficient Operations

Common Shortcuts Quick Reference

Function Shortcut (Win/Linux) Shortcut (Mac)
Duplicate current line Ctrl + D ⌘ + D
Delete current line Ctrl + Y ⌘ + Delete
Move line Alt + Shift + ↑/↓ ⌥ + ⇧ + ↑/↓
Quick fix suggestions Alt + Enter ⌥ + Enter
Go to definition Ctrl + B ⌘ + B
View parameter hints Ctrl + P ⌘ + P

Multi-line Editing and Batch Operations

Column Selection Mode

  1. HoldAlt(Win) or⌥(Mac) + mouse drag

  2. or useAlt + Shift + Insertto toggle column mode

Application scenarios:

# 批量修改多个变量前缀
old_name = 1    →  new_name = 1
old_value = 2   →  new_value = 2

Multi-cursor editing

  • HoldAlt+ mouse click (add multiple cursors)

  • orCtrl + G(Win)/ ⌘ + G(Mac) select the same word


Code Formatting and Refactoring

Auto-format Code

  1. Format current file:

    • Ctrl + Alt + L(Win/Linux)

    • ⌥ + ⌘ + L(Mac)

  2. Format selected code:

    • Select code → Right-click →Reformat Code

Configure formatting rules:
设置 → 编辑器 → 代码样式 → Python


Rename Variables/Functions (Safe Refactoring)

  1. Select identifier (variable/function name)

  2. Right-click → Refactor → Rename

  3. or shortcutShift + F6

  4. Enter new name → PressEnter

Effect:

  • All places referencing this identifier are updated synchronously

  • Supports cross-file renaming


Extract Method

Extract the selected code snippet as a new method:

  1. Select code block

  2. Ctrl + Alt + M(Win)/ ⌘ + ⌥ + M(Mac)

  3. Enter method name → Confirm

Example

# Before extraction
def process_data(data):
    cleaned = []
    for item in data:
        if item.is_valid():  # ← Select this part of the code
            cleaned.append(item)
    return cleaned

# After extraction
def process_data(data):
    cleaned = []
    for item in data:
        if is_valid_item(item):
            cleaned.append(item)
    return cleaned

def is_valid_item(item):  # ← Automatically generated new method
    return item.is_valid()

Inline

Inline the method/variable at the call site:

  1. Place the cursor on the method name/variable

  2. Ctrl + Alt + N(Win)/ ⌘ + ⌥ + N(Mac)

# 内联前
def calculate_discount(price):
    return price * 0.9

total = calculate_discount(100)  # ← 光标在此行

# 内联后
total = 100 * 0.9  # ← 方法调用被替换为实际代码

Advanced Editing Techniques

Live Templates

Quickly generate common code patterns:

  1. Enter abbreviation (e.g.iter) → PressTab

  2. Preset templates:

    • main→ Generateif __name__ == '__main__'

    • try→ Generate complete try-except block

Custom templates:
Settings → Editor → Live Templates

Entering iter in the code editor will display template information:


Code Intention Actions (Alt+Enter)

Quickly fix or optimize code based on context:

  • Automatically import missing packages

  • Convert string formats (f-string / format)

  • Optimize conditional expressions

Operation: Place the cursor at the warning/suggestion →Alt + Enter


Summary: Efficient Editing Workflow

  1. Writing phase:

    • Use code completion (Ctrl + Space) for quick input

    • Use dynamic templates to generate repetitive structures

  2. Optimization phase:

    • Format code (Ctrl + Alt + L)

    • useAlt + EnterQuickly fix issues

  3. Refactoring phase:

    • Extract method (Ctrl + Alt + M)

    • Safe rename (Shift + F6)

Other Extensions