Skip to content

Instantly share code, notes, and snippets.

@LeoHeo
Created August 2, 2016 05:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeoHeo/2e54cf7d00d0497f183a8382a3ebaf74 to your computer and use it in GitHub Desktop.
Save LeoHeo/2e54cf7d00d0497f183a8382a3ebaf74 to your computer and use it in GitHub Desktop.

python TextWrap

문제 제기

ABCDEFGHIJKLIMNOQRSTUVWXYZ 라는 문자열이 있다. 이 문자열을 n개씩(여기서는 4개라고 가정) 잘라서 아래와 같이 만들고 싶다.

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ  

어떤 방법을 써야할까?

누구나 생각할 수 있는 방법으로 가보자.

sample = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
separate_index = 4

for i, char in enumerate(sample):
    if i % separate_index == 0:
        print("\n", end="")
    print(char, end="")

정말 누구나 생각할 수 있는 방법이다. separate_index의 배수마다 newline을 넣어서 줄을 띄우는 방식이다.

python textwrap 사용

어떻게 하면 코드의 양을 줄일 수 있을까?

python 에서는 textwrap이라는걸 제공한다. 공식문서

textwrapper를 사용하면 아래처럼 쓸 수 있다.

import textwrap

sample = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
separate_index = 4

print(textwrap.fill(sample, separate_index))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment