Python中使用%操作符输出可变长度的%s

21 投票
4 回答
23149 浏览
提问于 2025-04-15 14:26

我想要做这个:

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

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

但是我想把里面的 10 替换成 max_title_width 的值。我该怎么用最“pythonic”的方式来实现呢?

4 个回答

3

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'

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

22

从Python 2.6开始,Python的内置字符串(str和unicode)类提供了一种新的方法,可以让你更复杂地替换变量和格式化值,这个方法叫做str.format(),详细信息可以参考PEP 3101。字符串模块中的Formatter类允许你创建和自定义自己的字符串格式化行为,使用的实现和内置的format()方法是一样的。

(...)

举个例子假设你想要一个替换字段,它的宽度由另一个变量决定

>>> "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)

我个人非常喜欢这些新的格式化方法,因为在我看来,它们更强大,也更容易阅读。

48

这段内容是从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  >
>>>

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

>>> 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)

撰写回答