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
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.
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.
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.
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.
You can prefix the size requirement with -
to left-justify:
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With