Python中没有像这样的自动格式化。 (.format
函数语法是从C#中借用的。)毕竟,Perl是“实用提取和报告语言”,而Python并不是为格式化报告而设计的。
您的输出可以使用textwrap
模块完成,例如,
from textwrap import fill
def formatItem(left, right):
wrapped = fill(right, width=41, subsequent_indent=' '*15)
return ' {0:<13}{1}'.format(left, wrapped)
...
>>> print(formatItem('0123', 'This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah.'))
This is some long text which would wrap
past the 80 column mark
and go onto the next line
number of times blah blah
blah.
请注意,这里假设“左”不跨越1行。更一般的解决方案是
from textwrap import wrap
from itertools import zip_longest
def twoColumn(left, right, leftWidth=13, rightWidth=41, indent=2, separation=2):
lefts = wrap(left, width=leftWidth)
rights = wrap(right, width=rightWidth)
results = []
for l, r in zip_longest(lefts, rights, fillvalue=''):
results.append('{0:{1}}{2:{5}}{0:{3}}{4}'.format('', indent, l, separation, r, leftWidth))
return "\n".join(results)
>>> print(twoColumn("I'm trying to format some strings for output on the command-line", "report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting."))
I'm trying to report style, and am looking for the
format some easiest method to format a string such
strings for that I can get automatic paragraph
output on the formatting.
command-line
它是做什么的?对于那些不了解Perl的人。 – kennytm 2010-06-22 19:23:15
@KennyTM - 特别是这个例子?没有太多只是输出一个数字表。我想处理包装一些字符串段。如果你手动执行这些操作,那么行缩进会变成真正的痛苦,所以我希望能够找到可以使用的东西。除非一些Python vodo可以解决这个问题,否则我期望... – Petriborg 2010-06-22 19:25:56