0

这是我的基本代码,但我不知道在 def 之后添加什么

def centre(s, width=70):
    lines = open ('poem.txt ', 'r'). readlines ()
    stripped = []
    for line in lines:
        stripped.append(line.strip())
4

2 回答 2

4

您可能想查看该str.format()功能。如果您阅读文档,您会发现它能够使文本居中:

>>> "{0:^40}".format(" Ministry of Silly Walks ")
'        Ministry of Silly Walks         '
>>> "{0:=^40}".format(" Ministry of Silly Walks ")
'======= Ministry of Silly Walks ========'
于 2013-10-15T20:20:10.327 回答
3

python提供了一种str.center(width[,fillchar])方法。

for line in lines:
   print(line.center(width))

或类似的

http://docs.python.org/3/library/stdtypes.html#string-methods

于 2013-10-15T20:25:35.647 回答