Search code examples
pythonstringformattingstring-formatting

Python: String formatting to the right side


Here is my source code:

def fibonacci_numbers():
  how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
  i = 0
  res = [0, 1]
  while i < how_many_numbers:
      res.append(sum(res[-2:]))
      print("{}. {}".format(i + 1, res[i]))
      i += 1


fibonacci_numbers()

The output now is:

How many Fibbonacci numbers you want print: 30
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
...
30. 514229

But I need something like that:

How many Fibbonacci numbers you want print: 30
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
...
30. 514229

and so on. It's depending for a numbers I choose. If i take 50 numbers so I need more spaces, but everything need to be placed to the right side.

How I can achieve this?

I tried with {:>width} and with .rjust method, but I can't get it.

Is there simple solution for that?

Or maybe I need make another loop and print there?

Final Solution:

Thanks for answers. I pick up some of them and i made this:

def fibonacci_numbers():

    how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
    i = 0
    res = [0, 1]
    while i < how_many_numbers:
        res.append(sum(res[-2:]))
        i += 1

    size_of_i = len(str(i))
    i = 0
    for num in res[:-1]:
        size = len(str(res[-2]))
        print("{:<{width_of_i}} {:>{width}}".format(str(i)+":", num, width_of_i=size_of_i + 1, width=size))
        i += 1



fibonacci_numbers()

Solution

  • Try to format both values:

    import math
    
    def fibonacci_numbers():
      how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
      i = 0
      res = [0, 1]
      for i in range(how_many_numbers):
          res.append(sum(res[-2:]))
      digits = int(math.log10(res[i]))+1
      ind_digits = int(math.log10(how_many_numbers-1))+2
      for i in range(how_many_numbers):
          print("{:<{ind_digits}} {:>{digits}}".format("{}.".format(i + 1), res[i], ind_digits=ind_digits, digits=digits))
    
    
    fibonacci_numbers()
    

    UPD: support fo variable length added.