Search code examples
pythonstringformattext-alignment

Align strings over a common character


I am looking for a simple, pythonic way of doing this with the minimum calculations and loops.

I have a bunch of strings, such as:

1 + 2 = 3

2*6 + 13 = 25

What I would like to print at the screen is:

xxx1 + 2 = 3

2*6 + 13 = 25

(where the x are actually spaces, but I could not figure out how to show it with this editor)

I am aware of string formatting with left and right align but this imply for each string to compute the number of spaces to add, convert it into a string, and inject this into the string alignment formatter, which seems complex.

Is there a simpler way?


Solution

  • Based on the information you provided, this may work:

    lst = [
    '1 + 2 = 3',
    '2*6 + 13 = 25',
    '2*6 = 12',
    '2 = 12 - 10'
    ]
    
    mxleft = max([e.index('=') for e in lst])
    
    l2 = [e.split('=')[0].rjust(mxleft) + '=' + e.split('=')[1] for e in lst]
    
    print('\n'.join(l2))
    

    Output

       1 + 2 = 3
    2*6 + 13 = 25
         2*6 = 12
           2 = 12 - 10