Python의 textwrap 모듈은 텍스트의 줄바꿈(wrap)과 채우기(fill) 작업을 수행하는 TextWrapper 클래스를 제공합니다. 또한 동일한 기능을 더 간편하게 사용할 수 있도록 몇 가지 편의 함수도 함께 제공하므로, 복잡한 설정 없이 손쉽게 텍스트 정렬 작업을 처리할 수 있습니다.
wrap(text)
wrap() 함수는 문자열로 전달된 단일 문단을 지정한 너비(width)에 맞춰 줄바꿈합니다. 각 줄이 최대 width 글자 수를 넘지 않도록 분할되며, 마지막 개행 문자(newline)가 포함되지 않은 출력 줄들의 리스트(list)를 반환합니다.
사용 예제
>>> 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.
위 예제에서는 width=50으로 설정했기 때문에, 원래 긴 한 문단이 50자 이내의 여러 줄로 자동 분할된 것을 확인할 수 있습니다.
fill(text)
fill() 함수 역시 단일 문단을 줄바꿈한다는 점에서 wrap()과 동일하지만, 결과를 리스트가 아닌 줄바꿈 문자(\n)가 포함된 하나의 문자열로 반환한다는 차이가 있습니다.
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.'
어떤 함수를 선택해야 할까?
두 함수의 차이를 정리하면 다음과 같습니다.
- wrap(): 줄바꿈된 각 라인을 요소로 갖는 리스트를 반환 → 줄 단위로 개별 처리할 때 유용
- fill(): 줄바꿈 문자가 포함된 단일 문자열을 반환 → 결과를 그대로 출력하거나 저장할 때 유용
참고로, 한두 개의 짧은 문자열만 처리할 경우에는 이러한 편의 함수만으로 충분합니다. 하지만 동일한 설정으로 많은 텍스트를 반복적으로 처리해야 한다면, 매번 함수를 호출하는 대신 TextWrapper 인스턴스를 한 번 생성해 재사용하는 것이 성능 면에서 더 효율적입니다.