Computer >> Máy Tính >  >> Lập trình >> Python

Textwrap - Gói và điền văn bản bằng Python

Mô-đun textwrap cung cấp lớp TextWrapper thực hiện việc gói hoặc lấp đầy. Nó có các chức năng tiện lợi cho cùng mục đích.

bọc (văn bản)

Gói một đoạn văn bản trong văn bản (một chuỗi) để mọi dòng dài nhất là ký tự chiều rộng. Trả về danh sách các dòng đầu ra, không có dòng mới cuối cùng.

điền (văn bản)

Gói đoạn văn bản đơn lẻ trong văn bản và trả về một chuỗi đơn chứa đoạn văn bản được gói gọn.

>>> 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.

Điền ví dụ

>>> 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.'