Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีขยายแท็บ (Tabs) ให้เป็นช่องว่างหลายช่องใน Python

ใช้เมธอด str.replace() หรือโมดูล re เพื่อแทนที่แท็บ (\t) ด้วยช่องว่าง

วิธีที่ 1: str.replace()

print('replace \t\t tabs in \t\t\t this string'.replace('\t', ' '))

วิธีที่ 2: re.sub()

import re
print(re.sub('\t', ' ', 'replace \t\ttabs in \t\t\t this string'))

ผลลัพธ์ทั้งคู่

replace tabs in this string

ทั้งสองวิธีลบแท็บออก หากต้องการแทนที่ด้วยหลายช่องว่าง ให้เปลี่ยน replacement string เป็น ' ' (4 spaces) ตามมาตรฐาน PEP 8