I just want fixed width columns of text but the strings are all padded right, instead of left!!?
sys.stdout.write("%6s %50s %25sn" % (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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can prefix the size requirement with - to left-justify:
sys.stdout.write("%-6s %-50s %-25sn" % (code, name, industry))
Method 2
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.
Method 3
sys.stdout.write("%-6s %-50s %-25sn" % (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 '
Method 4
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
Method 5
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.
Method 6
Use -50% instead of +50% They will be aligned to left..
Method 7
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)
Method 8
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])
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0