지금 개발하러갑니다

Python textwrap 모듈 본문

Python

Python textwrap 모듈

jspark1215 2020. 1. 12. 22:56
Python — textwrap 모듈

Python — textwrap 모듈

codefights에서 문제를 풀다가 아래와 같은 문제를 만나게 되었다.

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: each feedback 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 a feedbackand the size of the screen, splits the feedback 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.
For feedback = "This is an example feedback", and size = 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

'Python' 카테고리의 다른 글

Python, Python 패키지 설치 경로  (0) 2020.01.12
Comments