'Python Printing Diagonal Pattern

I want to print a diagonal pattern like this -

enter image description here

However, I'm able to get only this output -

enter image description here

Here is my code -

for i in range (0,5):
    for j in range(0,i):
        print(" ", end = "")
    print(i)
    print(" ")


Solution 1:[1]

You can prepare a string of spaces and print a substring of it on each line starting at the positon if the current index:

n = 4
spaces = " "*n
for i in range(n+1):
    print(spaces[i:],i)

     0
    1
   2
  3
 4

Solution 2:[2]

Store the number of spaces you need in every iteration with space = n - i(for number 0 you need 4 spaces). Insert the spaces before the actual number here i. The reason why you need n + 1 instead of n is because the range is up to but not include the second agrument.

n = 4

for i in range(n + 1):
    space = n - i
    print(f"{' ' * space}{i}")

output :

    0
   1
  2
 3
4

Solution 3:[3]

You don't need to run 2 loops, all you need is to count the number of spaces in every line and try to find the pattern of spaces and the numbers of stars:

n = 5
for i in range(0, n):
    print((n-i)*" "+str(i))
     0
    1
   2
  3
 4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alain T.
Solution 2
Solution 3 vinzee