我正在打印一些格式化的列.我想使用以下变量来设置我的 .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 - 在字符串格式化程序参数中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何制作一个在 Python 中提供角色的不和谐机器人How to make a discord bot that gives roles in Python?(如何制作一个在 Python 中提供角色的不和谐机器人?)
Discord 机器人没有响应命令Discord bot isn#39;t responding to commands(Discord 机器人没有响应命令)
你能得到“关于我"吗?Discord 机器人的功能?Can you Get the quot;About mequot; feature on Discord bot#39;s? (Discord.py)(你能得到“关于我吗?Discord 机器人的功能?(不和谐.py))
message.channel.id Discord PYmessage.channel.id Discord PY(message.channel.id Discord PY)
如何在 heroku 上托管我的 discord.py 机器人?How do I host my discord.py bot on heroku?(如何在 heroku 上托管我的 discord.py 机器人?)
discord.py - 自动更改角色颜色discord.py - Automaticaly Change an Role Color(discord.py - 自动更改角色颜色)