Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic border around text in python

Tags:

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.       |
+----------------------------+
like image 487
Dries Coppens Avatar asked Nov 14 '25 18:11

Dries Coppens


1 Answers

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.        |
+----------------------------+
like image 77
solarc Avatar answered Nov 17 '25 08:11

solarc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!