代码之家  ›  专栏  ›  技术社区  ›  mandroid

在Python Shell中将文本格式化为框

  •  1
  • mandroid  · 技术社区  · 15 年前

    我创建了一个基本菜单类,如下所示:

    class Menu:
        def __init__(self, title, body):
            self.title = title
            self.body = body
        def display(self):
            #print the menu to the screen
    

    我想做的是格式化标题和正文,使它们几乎可以放入预制框中。在那里,无论我通过什么作为身体,显示器将能够适应它里面。格式应该是这样的。

    ********************************************************************************
    *    Here's the title                                                          *
    ********************************************************************************
    *                                                                              *
    *  The body will go in here.  Say I put a line break here ---> \n              *
    *  it will go to the next line.  I also want to keep track\n                   *
    *  \t   <----- of tabs so I can space things out on lines if i have to         *
    *                                                                              *
    ********************************************************************************
    

    我想这个头衔会很容易,但我已经迷失在身体上了。

    2 回复  |  直到 15 年前
        1
  •  4
  •   John Kugelman Michael Hodel    15 年前
    #!/usr/bin/env python
    
    def format_box(title, body, width=80):
        box_line = lambda text: "*  " + text + (" " * (width - 6 - len(text))) + "  *"
    
        print "*" * width
        print box_line(title)
        print "*" * width
        print box_line("")
    
        for line in body.split("\n"):
            print box_line(line.expandtabs())
    
        print box_line("")
        print "*" * width
    
    format_box(
        "Here's the title",
    
        "The body will go in here.  Say I put a line break here ---> \n"
        "it will go to the next line.  I also want to keep track\n"
        "\t<----- of tabs so I can space things out on lines if i have to"
    );
    
        2
  •  0
  •   CrashCodes    15 年前

    你也可以试试标准的 'textwrap' 模块