問題描述
我正在打印一些格式化的列.我想使用以下變量來設置我的 .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模板網!