%s 的可变长度与 python 中的 % 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1448820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:15:59  来源:igfitidea点击:

variable length of %s with the % operator in python

python

提问by priestc

I'm trying to do this:

我正在尝试这样做:

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

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

But I want to replace the 10with the value of max_title_width. How do I do this in the most pythonic way possible?

但我想10max_title_width. 我如何以最 Pythonic 的方式做到这一点?

回答by PaulMcG

This is a carryover from the C formatting markup:

这是 C 格式标记的结转:

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

If you want left-justified text (for entries shorter than max_title_width), put a '-' before the '*'.

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

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

If the len field is shorter than the text string, the string just overflows:

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

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

If you want to clip at a maximum length, use the '.' precision field of the format placeholder:

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

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

Put them all together this way:

把它们放在一起:

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

回答by Esteban Küber

You have the new strings formatting methods from Python 3 and Python 2.6.

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

Starting in Python 2.6, the built-in str and unicode classes provide the ability to do complex variable substitutions and value formatting via the str.format() method described in PEP 3101. The Formatter class in the string module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method.

(...)

For example, suppose you wanted to have a replacement field whose field width is determined by another variable:

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

从 Python 2.6 开始,内置的 str 和 unicode 类提供了通过 PEP 3101 中描述的 str.format() 方法进行复杂变量替换和值格式化的能力。 string 模块中的 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     .


So for your example it would be

所以对于你的例子,它会是

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)

I personally love the new formatting methods, as they are far more powerful and readable in my humble opinion.

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

回答by Paulo Freitas

Python 2.6+ alternate version examples:

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'

Hint: first non-keyword args, then keyword args.

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

回答by SilentGhost

you could create your template outside of the loop:

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

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

You could also learn about the new formattingin python.

您还可以了解Python 中的新格式

and btw, maxdoesn't require a list, you can pass it an iterable:

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

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