我正在使用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
有什么方法可以使这段代码有效吗?重点是能够使用变量控制间距以确定填充量。
你应该把format_string
作为变量
temp = f'{i:{format_string}}' + temp
在您明确指出之前,:
之后的下一个代码不会被解析为变量。并感谢@timpietzcker链接到文档:formatted-string-literals
您需要保持对齐和填充标记彼此分开:
def display_pattern(n):
padding = 4
align = ">"
temp = ''
for i in range(1, n + 1):
temp = f'{i:{align}{padding}}' + temp
print(temp)
编辑:
我认为这不太正确。我做了一些测试,以下工作也是如此:
def display_pattern(n):
align = ">4"
temp = ''
for i in range(1, n + 1):
temp = f'{i:{align}}' + temp
print(temp)
所以我不能说为什么你的方法不起作用......