ブリブリ備忘録 おっ、python

HackerRankの問題とコメント(python3) 拙いですが...

Text Wrap

・問題

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

Input Format

The first line contains a string, 
The second line contains the width, .

Constraints

 

Output Format

Print the text wrapped paragraph.

Sample Input 0

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Sample Output 0

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

ソースコード

import textwrap
def wrap(string, max_width):
    result='\n'.join(textwrap.wrap(string, max_width))
    return result
if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

・コメント

与えられた長い文字列を、与えられた文字数ごとに改行する問題。

textwrap.wrap(string, max_width)

でstringをmax_widthごとに区切り、リストに入れることができる。

これをjoin()を用いて改行しながら出力すれば答えが得られる。

・URL

https://www.hackerrank.com/challenges/text-wrap/problem