17

我正在使用 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

有什么办法可以让这段代码工作吗?要点是能够使用变量来控制间距以确定填充量。

4

2 回答 2

22

你应该把format_stringas 变量

temp = f'{i:{format_string}}' + temp

:除非您明确指出,否则后面的下一个代码不会被解析为变量。并感谢 @timpietzcker 提供的文档链接:formatted-string-literals

于 2019-02-20T07:18:40.287 回答
3

您需要保持对齐和填充标记彼此分开:

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)

所以我真的不能说为什么你的方法不起作用......

于 2019-02-20T07:16:14.860 回答