Python3 - 在字符串格式化程序参数中使用变量 [英] Python3 - Use a variables inside string formatter arguments

查看:23
本文介绍了Python3 - 在字符串格式化程序参数中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打印一些格式化的列.我想使用以下变量来设置我的 .format 参数中的长度

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

我有

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. 也将名字用大括号括起来;和
  2. 将宽度作为关键字参数传递给 str.format.

例如:

>>> 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 不会在本地范围内查找适当的名称;它们必须显式传递.

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

(请注意,end 和任何其他显式关键字参数必须在 **widths 之前.)

(Note that end, and any other explicit keyword arguments, must come before **widths.)

这篇关于Python3 - 在字符串格式化程序参数中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆