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:
JavaScript
x
4
1
1 + 2 = 3
2
3
2*6 + 13 = 25
4
What I would like to print at the screen is:
JavaScript
1
4
1
xxx1 + 2 = 3
2
3
2*6 + 13 = 25
4
(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?
Advertisement
Answer
Based on the information you provided, this may work:
JavaScript
1
13
13
1
lst = [
2
'1 + 2 = 3',
3
'2*6 + 13 = 25',
4
'2*6 = 12',
5
'2 = 12 - 10'
6
]
7
8
mxleft = max([e.index('=') for e in lst])
9
10
l2 = [e.split('=')[0].rjust(mxleft) + '=' + e.split('=')[1] for e in lst]
11
12
print('n'.join(l2))
13
Output
JavaScript
1
5
1
1 + 2 = 3
2
2*6 + 13 = 25
3
2*6 = 12
4
2 = 12 - 10
5