【问题标题】:Equally separating words in Python在 Python 中相等地分隔单词
【发布时间】:2014-05-23 21:52:00
【问题描述】:

我想要做的是单独的文本块,以便我在每行中有两个块,并且在它们从同一点开始的不同行中。我正在使用它是我正在为自己的使用开发的一个小图书管理器程序,所以它应该看起来像这样:

Book Title Here                    Author Name Here
Little longer title here           Author Name Here
shorter here                       Author Name Here

我尝试使用 .ljust().rjust() 使用空格,但它并没有真正为我工作:无论出于何种原因,空格都不会均匀,我最终没有将标题堆叠在一起,而是相隔很少。

我正在使用 Tkinter 构建 GUI,每一行都应该是列表框中的一个项目。

【问题讨论】:

    标签: python string list listbox format


    【解决方案1】:

    我建议使用format mini-language,设置如下:

    bookdict = {
      'Little longer title here': 'Author Name Here',
      'Book Title Here': 'Another Author Name Here',
      'shorter here': 'Diff Name Here'}
    bookwidth = max(map(len, bookdict.keys()))
    authorwidth = max(map(len, bookdict.values()))
    

    format迷你语言

    还有这种迷你语言的用法:

    template = '{{0:<{bw}}} {{1:>{aw}}}'.format(bw=bookwidth, aw=authorwidth)
    for book, author in bookdict.items():
        print( template.format(book, author) )
    

    打印:

    Little longer title here         Author Name Here
    Book Title Here          Another Author Name Here
    shorter here                       Diff Name Here
    

    为了打破这一点,双括号将保留在第一种格式上并减少为单括号,并且单括号将成为计算的最大镜头的宽度,例如:

    '{0:<30} {1:>20}'
    

    小于 (&lt;) 表示左对齐,大于 (&gt;) 表示右对齐。

    rjustljust

    如果你真的想使用 str.rjust 和 str.ljust 方法:

    for book, author in bookdict.items():
        print(book.ljust(bookwidth) + ' ' + author.rjust(authorwidth))
    

    打印:

    Little longer title here         Author Name Here
    shorter here                       Diff Name Here
    Book Title Here          Another Author Name Here
    

    【讨论】:

    • 我试过了,打印的时候效果很好,但是当我把它插入列表框时,我真的不知道为什么,我猜它有与 tkinter 默认使用的字体有关
    • 确实如此,因为我更改了字体,您的解决方案对我来说效果很好。谢谢。
    【解决方案2】:

    如果您使用的是固定宽度字体,那么"{:40}{}".format("Book Title Here", "Author Name Here" 是您的朋友。 (将 40 更改为您想为第一部分分配的任何空间。)

    如果您使用的是可变宽度字体,那么您将希望使用 Tkinter 的排列方式来完成此操作,这可能归结为将每行的两个部分放在各自的部分中。

    例如,您可以执行以下操作:

    Label(master, text="Book Title Here").grid(row=0, sticky=W)
    Label(master, text="Author Name Here").grid(row=0, column=1, sticky=W)
    
    Label(master, text="Little longer title here").grid(row=1, sticky=W)
    Label(master, text="Author Name Here").grid(row=1, column=1, sticky=W)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多