【问题标题】:variable length of %s with the % operator in python在 python 中使用 % 运算符的 %s 可变长度
【发布时间】:2010-11-29 17:56:30
【问题描述】:

我正在尝试这样做:

max_title_width = max([len(text) for text in columns])

for column in columns:
    print "%10s, blah" % column

但我想用max_title_width 的值替换10。我该如何以最 Pythonic 的方式做到这一点?

【问题讨论】:

  • 在 Python 2.4 及更高版本中,在计算 max_title_width 时不需要 [] - 它们只是构建一个列表,您在计算最大值后立即丢弃该列表。见python.org/dev/peps/pep-0289

标签: python


【解决方案1】:

您拥有来自 Python 3 和 Python 2.6 的新字符串格式化方法。

从 Python 2.6 开始,内置的 str 和 unicode 类提供了通过 PEP 3101 中描述的 str.format() 方法进行复杂变量替换和值格式化的能力。字符串模块中的 Formatter 类允许您使用与内置 format() 方法相同的实现来创建和自定义您自己的字符串格式化行为。

(...)

For example假设您想要一个替换字段,其字段宽度由另一个变量确定

>>> "A man with two {0:{1}}.".format("noses", 10)
"A man with two noses     ."
>>> print("A man with two {0:{1}}.".format("noses", 10))
A man with two noses     .

所以你的例子是

max_title_width = max(len(text) for text in columns)

for column in columns:
    print "A man with two {0:{1}}".format(column, max_title_width)

我个人喜欢新的格式化方法,因为在我看来它们更强大且可读性更强。

【讨论】:

  • 我不知道你可以这样做...一开始我想说这感觉很不自然,但仔细想想,我觉得有道理!
【解决方案2】:

Python 2.6+ 备用版本示例:

>>> '{:{n}s}, blah'.format('column', n=10)
'column    , blah'
>>> '{:*>{l}s}'.format(password[-3:], l=len(password)) # password = 'stackoverflow'
'**********low'
>>> '{:,.{n}f} {}'.format(1234.567, 'USD', n=2)
'1,234.57 USD'

提示:首先是非关键字参数,然后是关键字参数。

【讨论】:

    【解决方案3】:

    这是 C 格式标记的遗留物:

    print "%*s, blah" % (max_title_width,column)
    

    如果您想要左对齐文本(对于短于max_title_width 的条目),请在“*”之前放置一个“-”。

    >>> text = "abcdef"
    >>> print "<%*s>" % (len(text)+2,text)
    <  abcdef>
    >>> print "<%-*s>" % (len(text)+2,text)
    <abcdef  >
    >>>
    

    如果 len 字段比文本字符串短,字符串就会溢出:

    >>> print "<%*s>" % (len(text)-2,text)
    <abcdef>
    

    如果您想以最大长度剪辑,请使用“.”格式占位符的精度字段:

    >>> print "<%.*s>" % (len(text)-2,text)
    <abcd>
    

    以这种方式将它们放在一起:

    %
    - if left justified
    * or integer - min width (if '*', insert variable length in data tuple)
    .* or .integer - max width (if '*', insert variable length in data tuple)
    

    【讨论】:

    • 哇,很棒的把戏!我不知道左/右填充。
    【解决方案4】:

    您可以在循环之外创建模板:

    tmpl = '%%%ds, blah' % max_title_width
    for column in columns:
        print tmpl % column
    

    您还可以了解python中的new formatting

    顺便说一句,max 不需要列表,您可以将其传递给可迭代对象:

    max_title_width = max(len(i) for i in columns)
    

    【讨论】:

    • max(columns, key=len) 从columns 返回一个元素。原始海报的代码获取最长列的length...
    • 很好,我在想什么。
    • 不是我,但可能是因为使用 * 说明符指定宽度更符合 Python 风格。
    • 嗯?更蟒蛇?他在循环中打印,如何使用晦涩的语法并在每次迭代时扩展星号更符合 Python 风格?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2018-03-03
    • 2020-06-03
    相关资源
    最近更新 更多