我想复制这个字符串:
这就是我的尝试,因为您可以看到值未正确对齐。我知道我需要使用某种类型的填充,但我所做的一切都失败了。
这是我的代码:
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张图像?
我认为这是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
在开始而不是结束时添加空间。
您只需要为每行中的第一个元素指定一个常量长度:
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
))