我正在使用 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
有什么办法可以让这段代码工作吗?要点是能够使用变量来控制间距以确定填充量。