hackerrank String 6 Text Wrap

Check Tutorial tab to know how to to solve.

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

My Answer

import textwrap

def wrap1(string, max_width):

    result=''
    count = len(string)/max_width

    for i in range(count):
         result = result + string[i * max_width: i * max_width + max_width] + '\n'
    if len(string) % max_width != 0:
        result = result + string[count * max_width:]
    return result

def wrap2(string, max_width):
    lists = textwrap.wrap(string, width=max_width)
    result=''
    for i in lists:
        result = result + i + '\n'
    return result

def wrap(string, max_width):
    lists = textwrap.wrap(string, width=max_width) 

    return '\n'.join(lists)


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

 

發佈了27 篇原創文章 · 獲贊 1 · 訪問量 5460
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章