在Python中的format()函数中使用变量 [英] Using variables in the format() function in Python
问题描述
是否可以在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字符串的优点是可以在字符串值语法本身中内联非常易读和紧凑的字符串格式.
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.
这篇关于在Python中的format()函数中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!