How to left align a fixed width string?

PythonString Formatting

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

Solution 2 - Python

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.

Solution 3 - Python

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                     '

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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

Solution 7 - Python

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)

Solution 8 - Python

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])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn MeeView Question on Stackoverflow
Solution 1 - PythonMatthew TrevorView Answer on Stackoverflow
Solution 2 - PythonMarwan AlsabbaghView Answer on Stackoverflow
Solution 3 - PythonJoran BeasleyView Answer on Stackoverflow
Solution 4 - Pythonuser1767754View Answer on Stackoverflow
Solution 5 - PythonkshaView Answer on Stackoverflow
Solution 6 - PythonRohit JainView Answer on Stackoverflow
Solution 7 - PythonNick SweetingView Answer on Stackoverflow
Solution 8 - PythoncodeRunner89View Answer on Stackoverflow