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