Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 502
John Mee Avatar asked Oct 02 '12 04:10

John Mee


People also ask

How do I left align some strings?

To align string to the left (spaces on the right) use formatting patern with comma (,) followed by a negative number of characters: String. Format(„{0,–10}“, text). To right alignment use a positive number: {0,10}. Following example shows how to format text to the table.

How do you left align a string in Python?

Alignment of Strings Using the format() Method in Python For the alignment of strings, we use the same syntax we used for the alignment of numbers. To left-align a string, we use the “:<n” symbol inside the placeholder.

How do you align a string in Python?

The syntax of the alignment of the output string is defined by '<', '>', '^' and followed by the width number. Example 1 : For Left Alignment output string syntax define '<' followed by the width number. Example 2 : For Right Alignment output string syntax define '>' followed by the width number.

How do you align columns in Python?

Use the just() Function to Print With Column Alignment in Python. In Python, we have different methods for string alignment. We can align the strings using the ljust() , rjust , and center() functions. Using these, we can align the rows appropriately based on our requirements.


1 Answers

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

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry)) 
like image 137
Matthew Trevor Avatar answered Oct 15 '22 01:10

Matthew Trevor