【问题标题】:Formatting string with padding使用填充格式化字符串
【发布时间】:2019-08-27 17:12:26
【问题描述】:

我正在尝试复制此字符串:

这就是我的尝试的样子,因为您可以看到这些值没有正确对齐。我知道我需要使用某种类型的填充,但我所做的一切都失败了。

这是我的代码:

individual_text = '''
Highest Individual Question Scores
        •       Leaders
                •       {}{:.2f}
                •       {}{:.2f}
                •       {}{:.2f}
        •       Colleagues
                •       {}{:.2f}
                •       {}{:.2f}
                •       {}{:.2f}
Lowest Individual Question Scores
        •       Leaders
                •       {}{:.2f}
                •       {}{:.2f}
                •       {}{:.2f}
        •       Colleagues
                •       {}{:.2f}
                •       {}{:.2f}
                •       {}{:.2f}
'''.format(top_3_leader.index[0], top_3_leader.values[0],
           top_3_leader.index[1], top_3_leader.values[1],
           top_3_leader.index[2], top_3_leader.values[2],
           top_3_colleague.index[0], top_3_colleague.values[0],
           top_3_colleague.index[1], top_3_colleague.values[1], 
           top_3_colleague.index[2], top_3_colleague.values[2],
           bottom_3_leader.index[0], bottom_3_leader.values[0],
           bottom_3_leader.index[1], bottom_3_leader.values[1],
           bottom_3_leader.index[2], bottom_3_leader.values[2],
           bottom_3_colleague.index[0], bottom_3_colleague.values[0],
           bottom_3_colleague.index[1], bottom_3_colleague.values[1],
           bottom_3_colleague.index[2], bottom_3_colleague.values[2]
          )

如何格式化我的文本,使其看起来像第一张图片?

【问题讨论】:

标签: python string format padding


【解决方案1】:

我认为这是strljust 方法的任务,请考虑以下示例:

x = [('text',1.14),('another text',7.96),('yet another text',9.53)]
for i in x:
    print(i[0].ljust(25)+"{:.2f}".format(i[1]))

输出:

text                     1.14
another text             7.96
yet another text         9.53

也存在rjust在开头而不是结尾添加空格。

【讨论】:

    【解决方案2】:

    您只需为每行中的第一个元素指定一个恒定长度:

    individual_text = '''
                    •       {:40}{:.2f}
                    •       {:40}{:.2f}
    '''.format('some_text', 3.86,
               'text_with_another_length', 3.85,
              )
    print(individual_text)
    
    # output:
    #               •       some_text                               3.86
    #               •       text_with_another_length                3.85
    

    您可以通过以下方式计算此长度:

    import itertools
    
    minimum_spaces = 3
    length = minimum_spaces + max(len(item) for item in itertools.chain(
        top_3_leader.index, top_3_colleague, bottom_3_leader, bottom_3_colleague
    ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-26
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      相关资源
      最近更新 更多