代码之家  ›  专栏  ›  技术社区  ›  lmiguelvargasf

如何将字符串格式作为变量传递给f字符串

  •  0
  • lmiguelvargasf  · 技术社区  · 6 年前

    我使用的是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
    

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

    0 回复  |  直到 6 年前
        1
  •  3
  •   Brown Bear    6 年前

    你应该把 format_string 作为变量

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

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

        2
  •  2
  •   Tim Pietzcker    6 年前

    您需要保持对齐标记和填充标记彼此独立:

    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)
    

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