Python3 - Use a variables inside string formatter arguments

主宰稳场 提交于 2019-12-20 03:03:36

问题


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.


回答1:


You need to:

  1. Wrap the names in braces, too; and
  2. 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.)




回答2:


I'd do it like this

In [11]: widths = dict(number=5, name=24, viewers=9)

In [12]: data = ('#', 'channel', 'viewers')

In [13]: '{:<{number}}{:<{name}}{:<{viewers}}'.format(*data, **widths)
Out[13]: '#    channel                 viewers  '

Of course, it's also possible to generate the format string, without actually getting it formatted:

In [14]: '{{:<{number}}}{{:<{name}}}{{:<{viewers}}}'.format(**widths)
Out[14]: '{:<5}{:<24}{:<9}'



回答3:


You can build your format string first

f = '{0:<%d}{1:<%d}{2:<%d}' % (number_length, name_length, viewers_length)
#produces
'{0:<5}{1:<24}{2:<9}'

Then use that in your other format call

print(f.format(' #','channel','viewers'), end = ''))


来源:https://stackoverflow.com/questions/28330657/python3-use-a-variables-inside-string-formatter-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!