Python3 - Use a variables inside string formatter arguments(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.
推荐答案
你需要:
- 也将名字用大括号括起来;和
- 将宽度作为关键字参数传递给
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 - 在字符串格式化程序参数中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python3 - 在字符串格式化程序参数中使用变量
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
