Sử dụng phương thức str.replace() hoặc module re để thay thế ký tự tab (\t) bằng khoảng trắng.
Cách 1: str.replace()
text = 'replace \t tabs in \t\t this string'
print(text.replace('\t', ' ')) # Thay tab bằng 4 spaces
Cách 2: re.sub()
import re
text = 'replace \t tabs in \t\t this string'
print(re.sub('\t', ' ', text))
Đầu ra
replace tabs in this string
Cách 3: str.expandtabs() (Built-in, khuyên dùng)
text = 'col1\tcol2\tcol3'
print(text.expandtabs(4)) # Tab stops mỗi 4 ký tự
print(text.expandtabs(8)) # Mặc định 8
Đầu ra
col1 col2 col3 col1 col2 col3
expandtabs() thông minh hơn: tính toán vị trí cột (tab stops) thay vì đơn giản thay thế.