1

假设我有这两个列表:

column1 = ["Attribute:","Virtual machine:","Troll:"]
column2 = ["A value associated with an object which is referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a.", 
           "A computer defined entirely in software. Python's virtual machine executes the bytecode emitted by the bytecode compiler.",
           "Someone who posts inflammatory, extraneous, or off-topic messages in an online community, such as a forum, chat room, or blog, with the primary intent of provoking readers into an emotional response or of otherwise disrupting normal on-topic discussion."]

这段代码:

for c1, c2 in zip(column1, column2):
    print "%-16s %s" % (c1, c2)

输出此文本:

Attribute:       A value associated with an object which is referenced by name u
sing dotted expressions. For example, if an object o has an attribute a it would
be referenced as o.a.
Virtual machine: A computer defined entirely in software. Python's virtual machi
ne executes the bytecode emitted by the bytecode compiler.
Troll:           Someone who posts inflammatory, extraneous, or off-topic messag
es in an online community, such as a forum, chat room, or blog, with the primary
 intent of provoking readers into an emotional response or of otherwise disrupti
ng normal on-topic discussion.

虽然我想要这样:

Attribute:       A value associated with an object which is referenced by name 
                 using dotted expressions. For example, if an object o has an 
                 attribute a it would be referenced as o.a.
Virtual machine: A computer defined entirely in software. Python's virtual 
                 machine executes the bytecode emitted by the bytecode compiler.
Troll:           Someone who posts inflammatory, extraneous, or off-topic 
                 messages in an online community, such as a forum, chat room, or 
                 blog, with the primary intent of provoking readers into an 
                 emotional response or of otherwise disrupting normal on-topic
                 discussion.

对于任何终端尺寸,我如何获得此结果?(有人告诉我,克林特可能很容易做到这一点,有人做过吗?)

注意:一个单词在行尾不被切碎的要求对我来说只是次要的。最重要的要求是让列表中的每个字符串元素以与该column2列表中每个元素的字符串开始处相同的水平间距继续。

4

2 回答 2

1
from clint.textui import puts, columns

width = 20

for term, definition in zip(column1, column2):
    puts(columns([term, width], [definition, None]))

...前缀以根据内容选择列宽:

#derive 1st column width from longest term
width = 0
for s in column1:
    if len(s) > width :
        width = len(s) + 1

改编自clint\examples\text_width.py。感谢您的提问;我以前不知道如何做到这一点,这是我将使用的东西。

于 2012-11-17T08:14:11.460 回答
1

这对我有用:

import textwrap

for c1, c2 in zip(column1, column2):
    mc2 = "".join(textwrap.fill(c2, width=50, initial_indent="", subsequent_indent="\t\t ", break_long_words = False))
    print "%-16s %s" % (c1, mc2)

获得相同结果的人将Clint获得投票而不是这个答案。

于 2012-08-24T11:01:05.933 回答