我想以左对齐方式(对齐)打印一些数据,但是在打印之前间距可能需要实时更改,因此我想使用变量而不是固定的硬编码空间宽度。
我尝试使用变量来容纳空格数,但这确实有效:
string_alignment_spacing = 15
print("|{:<string_alignment_spacing }|{:<string_alignment_spacing }|{:<string_alignment_spacing }|".format('Butter', 'Toast', 'Gravy'))
我希望得到以下输出:
|Butter |Toast |Gravy |
但是得到:
ValueError: Invalid format specifier
答案 0 :(得分:2)
在string_alignment_spacing
内和{}
方法中,将format()
设置关键字参数string_alignment_spacing=string_alignment_spacing
:
string_alignment_spacing = 15
print("|{:<{string_alignment_spacing}}|{:<{string_alignment_spacing}}|{:<{string_alignment_spacing}}|".format('Butter', 'Toast', 'Gravy', string_alignment_spacing=string_alignment_spacing))
打印:
|Butter |Toast |Gravy |
编辑(带有f字符串):
string_alignment_spacing = 15
print(f'|{"Butter":<{string_alignment_spacing}}|{"Toast":<{string_alignment_spacing}}|{"Gravy":<{string_alignment_spacing}}|')
答案 1 :(得分:0)
在以下代码中,string_alignment_spacing仅是str,后面有非法空格。
print("|{:<string_alignment_spacing }|{:<string_alignment_spacing }|{:<string_alignment_spacing }|".format('Butter', 'Toast', 'Gravy'))
尝试以下代码
formatstr = "|{:<%s}|{:<%s}|{:<%s}|"%(15,15,15)
print(formatstr.format('Butter', 'Toast', 'Gravy'))