在python中使用%运算符的%s的可变长度

pri*_*stc 20 python

我正在尝试这样做:

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

for column in columns:
    print "%10s, blah" % column
Run Code Online (Sandbox Code Playgroud)

但是我想要替换它10的值max_title_width.我怎么用最pythonic的方式做到这一点?

Pau*_*McG 46

这是C格式化标记的延续:

print "%*s, blah" % (max_title_width,column)
Run Code Online (Sandbox Code Playgroud)

如果你想要左对齐的文本(对于短于的条目max_title_width),在'*'之前放一个' - '.

>>> text = "abcdef"
>>> print "<%*s>" % (len(text)+2,text)
<  abcdef>
>>> print "<%-*s>" % (len(text)+2,text)
<abcdef  >
>>>
Run Code Online (Sandbox Code Playgroud)

如果len字段比文本字符串短,则字符串只是溢出:

>>> print "<%*s>" % (len(text)-2,text)
<abcdef>
Run Code Online (Sandbox Code Playgroud)

如果要剪切最大长度,请使用"." 格式占位符的精度字段:

>>> print "<%.*s>" % (len(text)-2,text)
<abcd>
Run Code Online (Sandbox Code Playgroud)

把它们放在一起这样:

%
- 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)
Run Code Online (Sandbox Code Playgroud)


Est*_*ber 22

您有Python 3和Python 2.6中的新字符串格式化方法.

从Python 2.6开始,内置的str和unicode类提供了通过PEP 3101中描述的str.format()方法执行复杂变量替换和值格式化的功能.字符串模块中的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     .
Run Code Online (Sandbox Code Playgroud)

所以对于你的例子来说就是这样

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)
Run Code Online (Sandbox Code Playgroud)

我个人喜欢新的格式化方法,因为在我的拙见中它们更强大,更易读.