Search code examples
pythonstring-formatting

How to left align a fixed width string?


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

Solution

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

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