티스토리 뷰

728x90

Text Wrap

Check Tutorial tab to know how to to solve.

You are given a string S and width W.
Your task is to wrap the string into a paragraph of width W.

Function Description

Complete the wrap function in the editor below.

wrap has the following parameters:

  • string string: a long string
  • int max_width: the width to wrap to

Returns

  • string: a single string with newline characters ('\n') where the breaks should be

Input Format

The first line contains a string, string.

The second line contains the width, .

Constraints

 

Sample Input 0

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Sample Output 0

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

 

문제해석

input으로 S라는 string값과 w라는width 값이 입력된다. string을 width 길이로 잘라서 출력하면 된다. 샘플에서는 ABCDEFGHIJKLIMNOQRSTUVWXYZ라는 string과 4라는 width가 입력되었으므로, ABCD, EFGH 이런 식으로 잘라서 출력이 되었다. 

문제풀이

코드 첫 번째 줄에 import textwrap 이라는 구문으로 힌트를 얻어서 검색을 해보았더니 textwrap.wrap()함수를 사용하면 간단히 문제풀이가 가능하였다. 문자열 래핑은 문자열이 너무 길어질 경우 특정 길이에서 줄바꿈을 하려고 할 때 사용할 수 있다고 한다. 아래는 참고한 링크이다. 

https://wikidocs.net/104608

 

textwrap.wrap() 함수는 리턴값으로 list를 반환하여 결과값이 아래와 같이 나왔다.

['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']

이것을 '\n'.join(wrap_text) 구문을 사용하여 줄바꿈해주도록 하였다. 

import textwrap

def wrap(string, max_width):
    wrap_text = textwrap.wrap(string, max_width)
    return '\n'.join(wrap_text)

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

Discussions

Discussions에서는 textwrap.wrap()함수를 사용하지 않고 for문을 사용하여 출력하였다.

def wrap(string, max_width):
    return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)])

 

728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함