gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:00:32 26 4
gpt4 key购买 nike

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

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

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.

最佳答案

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.'))
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 字符串格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3096402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com