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

Textwrap ใน Python: จัดรูปแบบข้อความ Wrap และ Fill

โมดูล textwrap ช่วยจัดรูปแบบข้อความยาวให้อ่านง่าย: wrap (แยกบรรทัด) และ fill (รวมเป็น string เดียว)

ฟังก์ชันหลัก

wrap(text, width=70)

คืน list of lines แต่ละบรรทัดไม่เกิน width

>> import textwrap
>>> sample = "The textwrap module provides convenience functions..."
>>> for line in textwrap.wrap(sample, width=50):
...     print(line)
The textwrap module provides convenience
functions, as well as TextWrapper class that
does all the work. If you're just wrapping or
filling one or two text strings, the convenience
functions should be good enough; otherwise, you
should use an instance of TextWrapper for efficiency.

fill(text, width=70)

คืน single string พร้อม newline (\n)

>> textwrap.fill(sample, width=50)
'The textwrap module provides convenience\nfunctions, as well as TextWrapper class that\ndoes all the work. If you're just wrapping or\nfilling one or two text strings, the convenience\nfunctions should be good enough; otherwise, you\nshould use an instance of TextWrapper for efficiency.'

TextWrapper Class (สำหรับใช้ซ้ำ/ปรับแต่ง)

>> wrapper = textwrap.TextWrapper(width=40, initial_indent="* ", subsequent_indent="  ")
>>> print(wrapper.fill(sample))
* The textwrap module provides
  convenience functions, as well as
  TextWrapper class that does all
  the work. If you're just wrapping
  or filling one or two text strings,
  the convenience functions should
  be good enough; otherwise, you
  should use an instance of
  TextWrapper for efficiency.

พารามิเตอร์สำคัญของ TextWrapper

ParameterDefaultคำอธิบาย
width70ความกว้างสูงสุดต่อบรรทัด
initial_indent""Indentation บรรทัดแรก
subsequent_indent""Indentation บรรทัดถัดไป
expand_tabsTrueแปลง tab เป็น space
replace_whitespaceTrueแทนที่ whitespace ด้วย space
break_long_wordsTrueตัดค่ายาวเกิน width
break_on_hyphensTrueตัดที่ hyphen
drop_whitespaceTrueลบ whitespace หน้า/หลังบรรทัด

ฟังก์ชันเพิ่มเติม

  • shorten(text, width, placeholder="...") - ตัดสั้นพร้อม placeholder
  • dedent(text) - ลบ common leading whitespace (สำหรับ docstrings)
  • indent(text, prefix) - เพิ่ม prefix ทุกบรรทัด
>> textwrap.shorten("Hello world this is long", width=15)
'Hello world...'

>>> textwrap.dedent("""    line1
...     line2""")
'line1\nline2'

>>> textwrap.indent("line1\nline2", ">> ")
'>> line1\n>> line2'