我正在使用f-strings,需要定义一个依赖于变量的格式。
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
有没有办法让这段代码工作?主要问题在于能否使用变量控制间距以确定填充量。
:
之后的下一行代码不会被解析为变量,除非您明确指示。 - Brown Bear