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

Textwrap - การตัดข้อความและการเติมข้อความใน Python


โมดูล textwrap มีคลาส TextWrapper ที่ทำการตัดหรือเติม มีฟังก์ชันอำนวยความสะดวกสำหรับจุดประสงค์เดียวกัน

ห่อ(ข้อความ)

ตัดย่อหน้าเดียวในข้อความ (สตริง) เพื่อให้ทุกบรรทัดมีความยาวอักขระความกว้างสูงสุด ส่งคืนรายการของบรรทัดผลลัพธ์ โดยไม่มีบรรทัดใหม่สุดท้าย

เติม(ข้อความ)

ตัดย่อหน้าเดียวในข้อความ และส่งกลับสตริงเดียวที่มีย่อหน้าที่ตัด

>>> sample_text = '''
The textwrap module provides some 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.
'''
>>> import textwrap
>>> for line in (textwrap.wrap(sample_text, width = 50)):
print (line)

The textwrap module provides some 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.

ตัวอย่างการกรอก

>>> textwrap.fill(sample_text, width = 50)
' The textwrap module provides some 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\nconvenience functions should be good enough;\notherwise, you should use an instance of\nTextWrapper for efficiency.'