【发布时间】:2019-07-13 19:03:11
【问题描述】:
我正在使用 f 字符串,我需要定义一个依赖于变量的格式。
def display_pattern(n):
temp = ''
for i in range(1, n + 1):
temp = f'{i:>3}' + temp
print(temp)
如果相关,display_pattern(5) 的输出为:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
我想知道是否可以操纵>3 的格式,并改为传递一个变量。例如,我尝试了以下方法:
def display_pattern(n):
spacing = 4
format_string = f'>{spacing}' # this is '>4'
temp = ''
for i in range(1, n + 1):
temp = f'{i:format_string}' + temp
print(temp)
但是,我收到以下错误:
Traceback (most recent call last):
File "pyramid.py", line 15, in <module>
display_pattern(8)
File "pyramid.py", line 9, in display_pattern
temp = f'{i:format_string}' + temp
ValueError: Invalid format specifier
有什么方法可以让这段代码工作吗?要点是能够使用变量来控制间距来确定填充量。
【问题讨论】: