How to left align a fixed width string?

John Mee picture John Mee · Oct 2, 2012 · Viewed 110.3k times · Source

I just want fixed width columns of text but the strings are all padded right, instead of left!!?

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

produces

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

but we want

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

Answer

Matthew Trevor picture Matthew Trevor · Oct 2, 2012

You can prefix the size requirement with - to left-justify:

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