Python3 - 在字符串格式器参数中使用一个变量 [英] Python3 - Use a variables inside string formatter arguments
问题描述
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ name_length = 24
viewers_length = 9
我有
$ b $ ('{0:< 5} {1:< 24} {2:9}'格式('#','channel',' '),end ='')
理想情况下,我希望像
$ b $
print('{0:< number_length} {1:< name_length} {2:< viewers_length}'。 '#','channel','viewers'),end ='')
我有一个无效的字符串格式化错误。
我已经尝试过%之前的变量和括号,但没有运气。
$ b $ ol <$> str.format
。例如:
>>> print({0:> {number_length}}。format(1,number_length = 8))
1
您也可以使用字典解包:
>>> widths = {'number_length':8}
>>> print({0:> {number_length}}。format(1,** widths))
1
str.format
不会在本地范围中寻找合适的名称;他们必须明确传递。
对于你的例子,这可以像这样工作:
>>> widths = {'number_length':5,
'name_length':24,
'viewers_length':9}
>>> template ='{0:< {number_length}} {1:< {name_length}} {2:< {viewers_length}}'
>>> print(template.format('#','channel','visitors',end ='',** widths))
#channel visitor
$ b <注意 end
和任何其他明确的关键字参数必须在 **宽度
。) I have some formatted columns that I'm printing. I would like to use the following variables to set the lengths in my .format arguments
number_length = 5
name_length = 24
viewers_length = 9
I have
print('{0:<5}{1:<24}{2:<9}'.format(' #','channel','viewers'), end = '')
Ideally I would like something like
print('{0:<number_length}{1:<name_length}{2:<viewers_length}'.format(
' #','channel','viewers'), end = '')
But this gives me an invalid string formatter error.
I have tried with % before the variables and parenthesis, but have had no luck.
You need to:
- Wrap the names in braces, too; and
- Pass the widths as keyword arguments to
str.format
.
For example:
>>> print("{0:>{number_length}}".format(1, number_length=8))
1
You can also use dictionary unpacking:
>>> widths = {'number_length': 8}
>>> print("{0:>{number_length}}".format(1, **widths))
1
str.format
won't look in the local scope for appropriate names; they must be passed explicitly.
For your example, this could work like:
>>> widths = {'number_length': 5,
'name_length': 24,
'viewers_length': 9}
>>> template= '{0:<{number_length}}{1:<{name_length}}{2:<{viewers_length}}'
>>> print(template.format('#', 'channel', 'visitors', end='', **widths))
# channel visitors
(Note that end
, and any other explicit keyword arguments, must come before **widths
.)
这篇关于Python3 - 在字符串格式器参数中使用一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!