Reputation: 52243
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
Upvotes: 91
Views: 158676
Reputation: 5891
A slightly more readable alternative solution:
sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)
Note that ljust(#ofchars)
uses fixed width characters and doesn't dynamically adjust like the other solutions.
(Also note that string addition with +
is significantly faster in modern Python than it was in the past, but you can swap out +
with ''.join(...)
if you still prefer that method out of habit)
Upvotes: 7
Reputation: 2087
With the new and popular f-strings in Python 3.6, here is how we left-align say a string with 16 padding length:
string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow ..
If you have variable padding length:
k = 20
print(f"{string:<{k}}..")
Stack Overflow ..
f-strings are more compact.
Upvotes: 37
Reputation: 25094
I definitely prefer the format
method more, as it is very flexible and can be easily extended to your custom classes by defining __format__
or the str
or repr
representations. For the sake of keeping it simple, i am using print
in the following examples, which can be replaced by sys.stdout.write
.
Simple Examples: alignment / filling
#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido")) # 'Guido '
print("{0:>10}".format("Guido")) # ' Guido'
print("{0:^10}".format("Guido")) # ' Guido '
We can add next to the align
specifies which are ^
, <
and >
a fill character to replace the space by any other character
print("{0:.^10}".format("Guido")) #..Guido...
Multiinput examples: align and fill many inputs
print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'
Advanced Examples
If you have your custom classes, you can define it's str
or repr
representations as follows:
class foo(object):
def __str__(self):
return "...::4::.."
def __repr__(self):
return "...::12::.."
Now you can use the !s
(str) or !r
(repr) to tell python to call those defined methods. If nothing is defined, Python defaults to __format__
which can be overwritten as well.
x = foo()
print "{0!r:<10}".format(x) #'...::12::..'
print "{0!s:<10}".format(x) #'...::4::..'
Source: Python Essential Reference, David M. Beazley, 4th Edition
Upvotes: 28
Reputation: 26778
This version uses the str.format method.
Python 2.7 and newer
sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))
Python 2.6 version
sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))
UPDATE
Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been removed from the docs.
Upvotes: 57
Reputation: 49
This one worked in my python script:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
Upvotes: 4
Reputation: 113948
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
on a side note you can make the width variable with *-s
>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple something '
Upvotes: 32
Reputation: 14952
You can prefix the size requirement with -
to left-justify:
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
Upvotes: 141