序列(字符串)乘法示例

本程序会在屏幕上打印一个由字符组成的“盒子”,而这个“盒子”在屏幕上居中而且能根据用户输入的句子自动调整大小。

代码可能看起来很复杂,但只使用基本的算法——计算出有多少空格、破折号等字符,然后将它们放置到合适的位置即可。

#以正确的宽度在居中的“盒子”内打印一个句子
#注意,整数除法运算符(//)只能用在Pythn2.2以及后续版本,在之前的版本中,只使用普通除法(/)

sentence=raw_input("Sentence: ")

screen_width=80
text_width=len(sentence)
box_width=text_width+6
left_margin=(screen_width-box_width)//2

print
print ' ' * left_margin+'+'+'-'*(box_width-4)+  '+'
print ' ' * left_margin+'|'+' '*text_width   +'  |'
print ' ' * left_margin+'|'+    sentence     +'  |'
print ' ' * left_margin+'|'+' '*text_width   +'  |'
print ' ' * left_margin+'+'+'-'*(box_width-4)+  '+'
print

sentence: He's a very naughty boy!

+-------------------------------  +
|                                         |
|He's a very naughty boy! |
|                                         |

+-------------------------------  +

原文地址:https://www.cnblogs.com/zzw818/p/7510949.html