0

My code output in python console looks sth like this:

1. 0
2. 1
...
10. 15
11. 37
12. 112
13. 4562

what to do to make it look like this:

1.     0
2.     1
...
10.   15
11.   37
12.  112
13. 4562

all numbers shifted toward right?

So here is the code:

i = 0
first = 0
sec = 1
fib = 0
numeration = 1
amount = int(input("How many numbers from Fibonacci sequence you want to     see?\n"))

print("Fibonacci sequence:")

for i in range(amount):
    print(str(numeration) + ".", fib)
    fib = first + sec
    sec = first
    first = fib
    i += 1
    numeration += 1
  • How are you printing? post your code. If you are talking about the console itself (not the print command) say which are you using (regular terminal, ipython, etc...). – kabanus Jun 05 '18 at 18:14
  • 1
    Do you know the contents of the entire sequence before you print the first value? If not, how do you know that the first value should be shifted four additional spaces? – Kevin Jun 05 '18 at 18:16
  • Please check this one : https://stackoverflow.com/questions/12684368/how-to-left-align-a-fixed-width-string – Taohidul Islam Jun 05 '18 at 18:24
  • It is worth noting that it is unnecessary to initialize i =0 and to increment it inside of the for loop. numeration seems to be unnecessary too, here you could just use i + 1 – d parolin Jun 05 '18 at 19:10

1 Answers1

1

Working from Python: Format output string, right alignment.

Replace

print(str(numeration) + ".", fib)

with

print("{:<3} {:>8}".format(str(numeration) + ".", fib))

This produces:

1.          0
2.          1
3.          1
4.          2
5.          3
6.          5
7.          8
8.         13
9.         21
10.        34
11.        55
12.        89
13.       144
14.       233
15.       377
16.       610
17.       987
18.      1597
19.      2584
20.      4181

The 3 specifies how wide a column you want for the numeration (including the .), and the 8 specifies the width of the right-aligned column for the Fibonacci number itself. > and < indicate right and left alignment, respectively.

Linuxios
  • 34,849
  • 13
  • 91
  • 116