使用填充格式化字符串

问题描述 投票:2回答:2

我想复制这个字符串:

enter image description here

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

enter image description here

这是我的代码:

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]
          )

如何将文本格式化为第1张图像?

python string format padding
2个回答
2
投票

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

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在开始而不是结束时添加空间。


1
投票

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

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
))
© www.soinside.com 2019 - 2024. All rights reserved.