在 Python 中的 format() 函数中使用变量

2022-01-12 00:00:00 python python-3.x formatting

问题描述

是否可以在 Python 的 format() 函数中使用格式说明符中的变量?我有以下代码,我需要 VAR 等于 field_size:

Is it possible to use variables in the format specifier in the format()-function in Python? I have the following code, and I need VAR to equal field_size:

def pretty_printer(*numbers):
  str_list = [str(num).lstrip('0') for num in numbers]

  field_size = max([len(string) for string in str_list])

  i = 1
  for num in numbers:
    print("Number", i, ":", format(num, 'VAR.2f')) # VAR needs to equal field_size


解决方案

你可以使用 str.format() 方法,它可以让你插入其他变量,比如宽度:

You can use the str.format() method, which lets you interpolate other variables for things like the width:

'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)

每个 {} 都是一个占位符,从关键字参数中填充命名值(您也可以使用编号的位置参数).可选的 : 之后的部分给出格式(基本上是 format() 函数的第二个参数),您可以使用更多 {} 占位符在那里填写参数.

Each {} is a placeholder, filling in named values from the keyword arguments (you can use numbered positional arguments too). The part after the optional : gives the format (the second argument to the format() function, basically), and you can use more {} placeholders there to fill in parameters.

使用编号位置如下所示:

Using numbered positions would look like this:

'Number {0}: {1:{2}.2f}'.format(i, num, field_size)

但您也可以将两者混合使用或选择不同的名称:

but you could also mix the two or pick different names:

'Number {0}: {1:{width}.2f}'.format(i, num, width=field_size)

如果省略数字和名称,字段会自动编号,所以下面的格式等价于前面的格式:

If you omit the numbers and names, the fields are automatically numbered, so the following is equivalent to the preceding format:

'Number {}: {:{width}.2f}'.format(i, num, width=field_size)

请注意,整个字符串是一个模板,因此 Number 字符串和冒号之类的内容是此处模板的一部分.

Note that the whole string is a template, so things like the Number string and the colon are part of the template here.

但是,您需要考虑到字段大小包括小数点;您可能需要调整大小以添加这 3 个额外字符.

You need to take into account that the field size includes the decimal point, however; you may need to adjust your size to add those 3 extra characters.

演示:

>>> i = 3
>>> num = 25
>>> field_size = 7
>>> 'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)
'Number 3:   25.00'

最后但同样重要的是,在 Python 3.6 及更高版本中,您可以使用 格式化字符串文字:

Last but not least, of Python 3.6 and up, you can put the variables directly into the string literal by using a formatted string literal:

f'Number {i}: {num:{field_size}.2f}'

使用常规字符串模板和 str.format() 的优点是您可以换出模板,f-strings 的优点是可以实现非常易读和紧凑的内联字符串格式在字符串值语法本身中.

The advantage of using a regular string template and str.format() is that you can swap out the template, the advantage of f-strings is that makes for very readable and compact string formatting inline in the string value syntax itself.

相关文章