簡體   English   中英

在Python中平均分隔單詞

[英]Equally separating words in Python

我想要做的是分開的文本塊,這樣我在每一行中都有兩個大塊,並且在不同的行中它們從同一點開始。 我正在使用的是一個小書管理器程序,我正在為自己的使用而開發,因此它看起來應該像這樣:

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

我嘗試使用帶空格的.ljust().rjust() ,但對我而言實際上並不起作用:無論出於何種原因,這些空格都不會均勻出現,並且最終我沒有將標題疊加在一起,但是相隔甚遠。

我正在使用Tkinter來構建GUI,並且每一行都應該是列表框中的一項。

我建議使用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}'

小於( < )表示左對齊,大於( > )表示右對齊。

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

如果您使用的是固定寬度的字體,則"{: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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM