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

Cách strip (loại bỏ) space/tab/newline bằng Python Regex

Để loại bỏ tất cả whitespace (space, tab, newline) khỏi chuỗi, dùng re.sub(r'\s+', '', text) hoặc re.findall(r'\S', text) để lấy chỉ non-whitespace.

Cách 1: re.sub - Thay thế whitespace bằng rỗng

import re

text = """I find     Tutorialspoint useful"""
cleaned = re.sub(r'\s+', '', text)
print(cleaned)
# IfindTutorialspointuseful

Cách 2: re.findall('\S') - Lấy tất cả non-whitespace


matches = re.findall(r'\S', text)
print(matches)
# ['I', 'f', 'i', 'n', 'd', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't', 'u', 's', 'e', 'f', 'u', 'l']

# Nối lại thành chuỗi
print(''.join(matches))
# IfindTutorialspointuseful

Cách 3: str.strip() / str.replace() - Nhanh hơn cho trường hợp đơn giản


# Chỉ strip đầu/cuối
text.strip()

# Xóa TẤT CẤT whitespace (builtin, nhanh hơn regex)
''.join(text.split())  # Tách theo whitespace rồi join
# Hoặc
text.replace(' ', '').replace('\n', '').replace('\t', '')

So sánh hiệu năng

Phương phápTốc độDùng khi
''.join(text.split())Nhanh nhấtXóa tất cả whitespace, không cần regex
re.sub(r'\s+', '', text)Trung bìnhCần regex pattern phức tạp hơn
re.findall(r'\S', text)ChậmCần xử lý từng ký tự non-whitespace

Lưu ý

  • \S = [^\s] = non-whitespace character.
  • strip() chỉ xóa đầu/cuối, split() không tham số xóa tất cả whitespace và gom lại.
  • Regex hữu ích khi cần logic phức tạp (ví dụ: xóa whitespace KHÔNG ở trong quotes).