Python基礎教程2-3:以正確的寬度在置中的“盒子”內列印一個句子,python基礎教程
程式碼範例:
#擷取句子長度
sentence = input('Plese input a sentence:')#He's very naughty boy
screen_width =100
#擷取文本的長度
text_width =len(sentence)
#文本的寬度
box_width = text_width +10
#計算出左右兩邊需空餘的格式數[左邊緣,右邊緣]
left_margin = (screen_width - box_width)//2
box_left_margin = (box_width-text_width)//2
#列印螢幕寬度
print('='*100)
print(' '*left_margin + '+' + '-' *(box_width-2) + '+')
print(' '*left_margin + '|' + ' ' *(box_width-2) + '|')
print(' '*left_margin + '|' + ' '*(box_left_margin-1) + sentence + ' '*(box_left_margin-1) + '|')
print(' '*left_margin + '|' + ' ' *(box_width-2) + '|')
print(' '*left_margin + '+' + '-' *(box_width-2) + '+')
#列印螢幕寬度
print('='*100)
運行結果:
Plese input a sentence:I love you Fiona
====================================================================================================
+------------------------+
| |
| I love you Fiona |
| |
+------------------------+
====================================================================================================