Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách xóa tab và newline bằng Python Regex

Dùng re.sub() với pattern \s+ (một hoặc nhiều whitespace) để thay thế tất cả tab, newline, space liên tiếp bằng một space đơn.

Ví dụ cơ bản

import re

text = """I find 
         Tutorialspoint 
         helpful"""

# Thay thế mọi chuỗi whitespace (space, tab, newline) bằng 1 space
cleaned = re.sub(r'\s+', ' ', text)
print(cleaned)
# I find Tutorialspoint helpful

Kết quả

I find Tutorialspoint helpful

Các biến thể

# Chỉ xóa, không thay bằng space (nối các từ lại)
re.sub(r'\s+', '', text)  
# "IfindTutorialspointhelpful"

# Chỉ xóa newline và tab, giữ space
re.sub(r'[\n\t]+', ' ', text)

# Giữ nguyên space đơn, chỉ gom nhiều space thành 1
re.sub(r' {2,}', ' ', text)  # Chỉ space, không tab/newline

Lưu ý

  • \s khớp: space, tab (\t), newline (\n), carriage return (\r), form feed (\f), vertical tab (\v).
  • \s+ gom nhóm whitespace liên tiếp thành 1 match.
  • re.sub trả về string mới, không sửa inplace.
  • Flag re.MULTILINE không ảnh hưởng \s.