Python 以正确的宽度在盒子中居中打印一个字符

注意://为整除的意思

代码:

# -*- coding:UTF-8 -*-
sentence = input("Sentence:")

screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width)//2
inner_margin = (box_width-text_width-2)//2
print
print (' ' * left_margin + '+' + '-' * (box_width-2)    + '+')
print (' ' * left_margin + '|' + ' ' * (box_width-2)    + '|')
print (' ' * left_margin + '|' + ' ' * inner_margin     + sentence + inner_margin * ' '+'|')
print (' ' * left_margin + '|' + ' ' * (box_width-2)    + '|')
print (' ' * left_margin + '+' + '-' * (box_width-2)    + '+')
print

执行结果:

 

posted @ 2016-11-18 15:24  OLIVER_QIN  阅读(1947)  评论(0编辑  收藏  举报