-2

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?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Milan
  • 1,547
  • 1
  • 24
  • 47

2 Answers2

1

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
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

if you know the maximum size of string before the equal signal you can split the string int the signal and then joint it using the format method (https://pyformat.info/). If you don't know you will have to check for it first and the best way to do this depends on how you are storing your strings.

string = '1+4+3=2'
split = string.split('=')

new_string = '{:>10}={}'.format(*split)
Flavio Moraes
  • 1,331
  • 1
  • 5
  • 16