使用 Python 的格式规范迷你语言打印带有变量的空格



我尝试打印以使用变量打印带有规范迷你语言的空间。

例如:

而不是这个

print('{:>10}'.format('hello'))

我想这样做:

i = 10
print('{:>i}'.format('hello'))

我收到此错误:

值错误:类型为"str"的对象出现未知格式代码"i">

i放在括号中,并将其添加到格式参数中,如下所示:

i = 10
print('{:>{i}}'.format('hello', i=i))
#      hello

可以这样做:

print(('{:>' + str(i) +'}').format('hello'))

您可以像这样创建自己的格式字符串:

i = 10
format_string = '{:>' + str(i) + '}'
print(format_string .format('hello'))

最新更新