Q:

Align two strings perfectly (python)

Is it possible to align the spaces and characters of two strings perfectly?
I have two functions, resulting in two strings.
One just adds a " " between a list of digits:
digits = 34567
new_digits = 3 4 5 6 7

The second function takes the string and prints out the index of the string, such that:
digits = 34567
index_of_digits = 1 2 3 4 5 

Now the issue that I am having is when the length of the string is greater than 10, the alignment is off:

I am supposed to get something like this:

Please advice.

A:

If your digits are in a list, you can use format to space them uniformly:
L = [3,4,2,5,6,3,6,2,5,1,4,1]
print(''.join([format(n,'3') for n in range(1,len(L)+1)]))
print(''.join([format(n,'3') for n in L]))

Or with f-string formatting (Python 3.6+):
L = [3,4,2,5,6,3,6,2,5,1,4,1]
print(''.join([f'{n+1:3}' for n in range(len(L))]))
print(''.join([f'{n:3}' for n in L]))

Output:
  1  2  3  4  5  6  7  8  9 10 11 12
  3  4  2  5  6  3  6  2  5  1  4  1

Ref: join, format, range, list comprehensions

