Форматирование строки с отступом - PullRequest
2 голосов
/ 05 апреля 2019

Я пытаюсь повторить эту строку:

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

Как мне отформатировать текст, чтобы он выглядел как первое изображение?

Ответы [ 2 ]

2 голосов
/ 05 апреля 2019

Я думаю, что это задача для 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 голос
/ 05 апреля 2019

Вам просто нужно указать одну постоянную длину для первого элемента в каждой строке:

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