Q:

Dynamic border around text in python

I need to input a sentence and make a dynamic border around that sentence. The border needs to have a width that is inputted. When the length of the sentence is higher than the given width, a new line has to be printed and the border has to change in height. The sentence also has to be centered in the dynamic border
I already tried this: 
sentence = input()
width = int(input())

length_of_sentence = len(sentence)

print('+-' + '-'*(width) + '-+')

for letter in sentence:
    print('| {0:^{1}} |'.format(letter, width - 4))

print('+-' + '-'*(width) + '-+')

but then each letter with a new line is printed and that's not what I need.
A great example is the following;
Input 
sentence = "You are only young once, but you can stay immature indefinitely."
width = 26

Output
+----------------------------+
| You are only young once, b |
| ut you can stay immature i |
|         ndefinitely.       |
+----------------------------+

A:

You can also use textwrap.wrap if you want to avoid breaking words in the middle:
from textwrap import wrap

sentence = input('Sentence: ')
width = int(input('Width: '))

print('+-' + '-' * width + '-+')

for line in wrap(sentence, width):
    print('| {0:^{1}} |'.format(line, width))

print('+-' + '-'*(width) + '-+')

Outputs:
+----------------------------+
|  You are only young once,  |
| but you can stay immature  |
|       indefinitely.        |
+----------------------------+

A:

So instead of doing a letter-wise input, you'd want to split the string into chunks of width letters. Taking the accepted answer:
def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

sentence = input('Sentence: ')
width = int(input('Width: '))

print('+-' + '-' * width + '-+')

for line in chunkstring(sentence, width):
    print('| {0:^{1}} |'.format(line, width))

print('+-' + '-'*(width) + '-+')

Example run:
Sentence: You are only young once, but you can stay immature indefinitely. 
Width: 26
+----------------------------+
| You are only young once, b |
| ut you can stay immature i |
|       ndefinitely.         |
+----------------------------+

