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
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…