【发布时间】:2020-03-20 03:09:42
【问题描述】:
我尝试使用 Specification Mini-Language 和变量来打印空格。
例如:
而不是这个
print('{:>10}'.format('hello'))
我想这样做:
i = 10
print('{:>i}'.format('hello'))
我得到这个错误:
ValueError:“str”类型的对象的未知格式代码“i”
【问题讨论】:
标签: python
我尝试使用 Specification Mini-Language 和变量来打印空格。
例如:
而不是这个
print('{:>10}'.format('hello'))
我想这样做:
i = 10
print('{:>i}'.format('hello'))
我得到这个错误:
ValueError:“str”类型的对象的未知格式代码“i”
【问题讨论】:
标签: python
将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'))
【讨论】: