小编典典

如何左对齐固定宽度的字符串?

python

我只想要固定宽度的文本列,但所有字符串都在右侧填充,而不是左侧!

 sys.stdout.write("%6s %50s %25s\n" % (code, name, industry))

产生

BGA                                BEGA CHEESE LIMITED   Food Beverage & Tobacco
BHP                               BHP BILLITON LIMITED                 Materials
BGL                               BIGAIR GROUP LIMITED Telecommunication Services
BGG           BLACKGOLD INTERNATIONAL HOLDINGS LIMITED                    Energy

但是我们想要

BGA BEGA CHEESE LIMITED                                Food Beverage & Tobacco
BHP BHP BILLITON LIMITED                               Materials
BGL BIGAIR GROUP LIMITED                               Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED           Energy

阅读 151

收藏
2020-12-20

共1个答案

小编典典

您可以在尺寸要求前加上-左对齐:

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
2020-12-20