Search code examples
pythonstring-formatting

Python text formatting to vertically align fields


Need some help with Python string formatting
I have two code:

a = "Hello"
b = False
p = "Python rocks"
q = True

I want to print a,b,p & q like this:

Hello ................................. False
Python rocks .......................... True

The total length of each line (From Hello to False) is fixed say 70 chars.

(edit) Following was being tried. Clearly not a good way (and incorrect), hence the question

arr = [ ["Hello", False], ["Python rocks", True]]
totallen = 70

for e in arr:
    result = "{0}".format(e[1])
    dottedlen = totallen - len(e[0]) - len(result) - 2
    dottedstr = "." * dottedlen
    str = "".join([e[0], " ", dottedstr, " ", result])
    print str

Solution

  • Use string formatting:

    In [48]: def solve(a,b):
        a,b=str(a),str(b)
        spaces=len(a.split())-1
        return "{0} {1} {2}".format(a,"."*(68-len(a)-len(b)-spaces),b)
       ....: 
    
    In [49]: print solve(a,b);print solve(p,q)
    Hello .......................................................... False
    Python rocks ................................................... True