1

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:

This is what I am getting

I am supposed to get something like this:

What I am supposed to get

Please advice.

2
  • I have managed to complete the assignment, which was to make a memory game - in which the player has to match the pars of number / digits. The only thing left for me to do is figure out how to align the index number with the digit itself. Commented Jan 18, 2016 at 5:48
  • Show your current formatting code. How are the numbers stored? Commented Jan 18, 2016 at 7:16

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! That fixed my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.