段落的Python字符串格式化程序

2024-10-05 10:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在命令行、报表样式上设置一些字符串的输出格式,并正在寻找设置字符串格式的最简单方法,以便能够获得自动段落格式。

在perlform中,格式化是通过“format”函数完成的

format Something =
    Test: @<<<<<<<< @||||| @>>>>>
            $str,     $%,    '$' . int($num)
.

$str = "widget";
$num = $cost/$quantity;
$~ = 'Something';
write;

perlform的变体允许文本被干净地包装,对于帮助屏幕、日志报告等非常有用。

有与python等价的吗?或者我可以使用Python的新字符串format函数编写一个合理的hack?

示例输出我希望:

Foobar-Title    Blob
  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.
  hi there      dito
  something     more text here. more text here. more text
                here.

Tags: the函数字符串text命令行formathere报表
3条回答

Python中没有这样的自动格式化。(函数语法是从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.'))
  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.

注意,这假设“左”不跨越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   

python文档中的thisthis可能有帮助。

import textwrap
import itertools

def formatter(format_str,widths,*columns):
    '''
    format_str describes the format of the report.
    {row[i]} is replaced by data from the ith element of columns.

    widths is expected to be a list of integers.
    {width[i]} is replaced by the ith element of the list widths.

    All the power of Python's string format spec is available for you to use
    in format_str. You can use it to define fill characters, alignment, width, type, etc.

    formatter takes an arbitrary number of arguments.
    Every argument after format_str and widths should be a list of strings.
    Each list contains the data for one column of the report.

    formatter returns the report as one big string.
    '''
    result=[]
    for row in zip(*columns):
        lines=[textwrap.wrap(elt, width=num) for elt,num in zip(row,widths)]
        for line in itertools.izip_longest(*lines,fillvalue=''):
            result.append(format_str.format(width=widths,row=line))
    return '\n'.join(result)

例如:

widths=[17,41]
form='{row[0]:<{width[0]}} {row[1]:<{width[1]}}'

titles=['Foobar-Title','0123','hi there','something']
blobs=['Blob','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.','dito','more text here. more text here. more text here.']

print(formatter(form,widths,titles,blobs))

收益率

# Foobar-Title      Blob                                     
# 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.
# hi there          dito                                     
# something         more text here. more text here. more text
#                   here.                                    

formatter可以接受任意数量的列。

相关问题 更多 >

    热门问题