Python — textwrap 모듈
Python — textwrap 모듈
codefights에서 문제를 풀다가 아래와 같은 문제를 만나게 되었다.
You’ve launched a revolutionary service not long ago, and were busy improving it for the last couple of months. When you finally decided that the service is perfect, you remembered that you created a feedbacks page long time ago, which you never checked out since then. Now that you have nothing left to do, you would like to have a look at what the community thinks of your service.
Unfortunately it looks like the feedbacks page is far from perfect: eachfeedback
is displayed as a one-line string, and if it's too long there's no way to see what it is about. Naturally, this horrible bug should be fixed. Implement a function that, given afeedback
and thesize
of the screen, splits thefeedback
into lines so that:
each token (i.e. sequence of non-whitespace characters) belongs to one of the lines entirely;
each line is at most size
characters long;
no line has trailing or leading spaces;
each line should have the maximum possible length, assuming that all lines before it were also the longest possible.
Forfeedback = "This is an example feedback"
, andsize = 8
,
the output should be
feedbackReview(feedback, size) = ["This is",
"an",
"example",
"feedback"]
문제를 정리하자면, 문단에서의 한줄이 주어진 size가 넘지 않도록 하는것인데, python textwrap 모듈에는 이러한 기능을 기본적으로 가진 함수가 있었다.
바로 textwrap.wrap 함수이다.
사용 예제는 다음과 같다.
코드)
import textwrap
sample = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
separate_index = 4
print(textwrap.fill(sample, separate_index))
결과)
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ