How to align a fixed-width string?

I just need columns with a fixed width of text, but all rows are filled on the right, not the 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 
+56
python string-formatting
Oct 02
source share
8 answers

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

 sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry)) 
+104
Oct 02
source share

This version uses the str.format method.

Python 2.7 and newer

 sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry)) 

Python version 2.6

 sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry)) 

UPDATE

Earlier in the documents it was said that the% operator is removed from the language in the future. This expression has been removed from documents .

+41
Oct 02
source share
 sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry)) 

on a side note, you can make a width variable with *-s

 >>> d = "%-*s%-*s"%(25,"apple",30,"something") >>> d 'apple something ' 
+26
Oct 02
source share

Use -50% instead of +50% They will be left aligned.

+9
Oct 02
source share

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 str or repr . For ease of use, I use print in the following examples, which can be replaced with sys.stdout.write .

Simple examples: alignment / padding

 #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 align parameters, which are ^ , < and > the fill character, to replace the space with any other character

 print("{0:.^10}".format("Guido")) #..Guido... 

Multiple Input Examples: Align and Fill Many Inputs

 print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum")) #'Product............. ...............Price ........Sum.........' 

Extended examples

If you have custom classes, you can define its str or repr views as follows:

 class foo(object): def __str__(self): return "...::4::.." def __repr__(self): return "...::12::.." 

Now you can use !s (str) or !r (repr) to tell python to call these specific methods. If nothing is defined, Python defaults to __format__ , which can also be overwritten. x = foo ()

 print "{0!r:<10}".format(x) #'...::12::..' print "{0!s:<10}".format(x) #'...::4::..' 

Source: Python Base Link, David M. Baisley, 4th Edition

+7
Dec 12 '17 at 22:44
source share

With new and popular f-lines in Python 3.6, here's how we left-aligned, say, a string with a fill length of 16:

 string = "Qaru" print(f"{string:<16}..") Qaru .. 

If you have a variable indent length:

 k = 20 print(f"{string:<{k}}..") Qaru .. 

f-lines are more readable.

+5
Feb 09 '19 at 9:45
source share

This worked on 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]) 
+4
Nov 12 '13 at 17:14
source share

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 is not dynamically configured like other solutions.

+3
May 10 '13 at 7:39
source share



All Articles