Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Textwrap - Góc gói và Điền văn bản (Text wrapping and filling) trong Python


Module textwrap cung cấp lớp TextWrapper thực hiện việc gói (wrapping) hoặc điền (filling). Nó có các hàm tiện ích cho cùng mục đích.

wrap(text)

Gói đoạn văn đơn trong text (một chuỗi) sao cho mỗi dòng dài tối đa width ký tự. Trả về danh sách các dòng đầu ra, không có ký tự newline cuối cùng.

fill(text)

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

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

Ví dụ fill

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