【问题标题】:Format string dynamically [duplicate]动态格式化字符串[重复]
【发布时间】:2011-05-17 04:10:54
【问题描述】:

如果我想让我的格式化字符串动态可调,我可以更改以下代码

print '%20s : %20s' % ("Python", "Very Good")

width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")

但是,这里的字符串连接似乎很麻烦。还有其他方法可以简化事情吗?

【问题讨论】:

    标签: python string


    【解决方案1】:

    您可以使用str.format() 方法执行此操作。

    >>> width = 20
    >>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
                  Python :            Very Good
    

    从 Python 3.6 开始,您可以使用 f-string 来执行此操作:

    In [579]: lang = 'Python'
    
    In [580]: adj = 'Very Good'
    
    In [581]: width = 20
    
    In [582]: f'{lang:>{width}}: {adj:>{width}}'
    Out[582]: '              Python:            Very Good'
    

    【讨论】:

      【解决方案2】:

      您可以从参数列表中获取填充值:

      print '%*s : %*s' % (20, "Python", 20, "Very Good")
      

      您甚至可以动态插入填充值:

      width = 20
      args = ("Python", "Very Good")
      padded_args = zip([width] * len(args), args)
      # Flatten the padded argument list.
      print "%*s : %*s" % tuple([item for list in padded_args for item in list])
      

      【讨论】:

        【解决方案3】:

        对于那些想用 python 3.6+ 和f-Strings 做同样事情的人来说,这是解决方案。

        width = 20
        py, vg = "Python", "Very Good"
        print(f"{py:>{width}s} : {vg:>{width}s}")
        

        【讨论】:

        • 谢谢。这正是我想要的。另一个问题,变量前面的“>”有什么作用?我见过前面有“0”的其他人。有什么意义吗?
        • 其实我刚刚找到了我的答案。 '>' 和 'cis.bentley.edu/sandbox/wp-content/uploads/…
        【解决方案4】:
        print '%*s : %*s' % (width, 'Python', width, 'Very Good')
        

        【讨论】:

        • +1 这是比我更好的答案。我正在研究 ljust 和 rjust 函数来做到这一点。
        【解决方案5】:

        如果您不想同时指定宽度,您可以提前准备一个格式字符串,就像您之前所做的那样 - 但需要进行另一个替换。我们使用%% 来转义字符串中的实际 % 符号。当宽度为 20 时,我们希望在格式字符串中以 %20s 结尾,因此我们使用 %%%ds 并提供宽度变量以替换其中。前两个 % 符号变成文字 %,然后用变量替换 %d。

        因此:

        format_template = '%%%ds : %%%ds'
        # later:
        width = 20
        formatter = format_template % (width, width)
        # even later:
        print formatter % ('Python', 'Very Good')
        

        【讨论】:

        • 我喜欢这种动态生成格式字符串的方法。但是,如果只动态插值字段宽度,Hamidi 先生的方法会更好。
        猜你喜欢
        • 2015-01-07
        • 2014-09-24
        • 2013-12-10
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多