Printing a Centered Triangle in Python

Test yourself first: can you print a centered triangle?
Python
Programming
Author

Salman Naqvi

Published

October 12, 2026

Here, I demonstrate my process in working out a centered triangle. If you have a cooler way to print one, let me know!

I’ll begin by printing a regular 5x5 grid. A 5x5 grid has 5 rows. So I’ll work with rows. A row has 5 elements.

print('.'*5)
.....

We repeat this 5 times to get a 5x5 grid.

dim = 5
for n in range(dim):
    seg = '.'*dim
    print(seg)
.....
.....
.....
.....
.....

We could make this into a one liner.

print('\n'.join('.'*dim for n in range(dim)))
.....
.....
.....
.....
.....

The next most simplest action I can take is to print a right triangle. This is matter of successively printing \(x+1\) items.

l = 5
for n in range(l): print('X'*n)

X
XX
XXX
XXXX

We need to adjust l by 1.

for n in range(1,l+1): print('X'*n)
X
XX
XXX
XXXX
XXXXX

What if I want to print . as padding for those spaces where the triangle doesn’t exist? If a row contains 5 elements,

for n in range(1,l+1): print(f'{l-n=}')
l-n=4
l-n=3
l-n=2
l-n=1
l-n=0
for n in range(1,l+1): 
    padding = l-n
    print('X'*n + '.'*padding)
X....
XX...
XXX..
XXXX.
XXXXX

In 1 line.

print('\n'.join('X'*n + '.'*(l-n) for n in range(1,l+1)))
X....
XX...
XXX..
XXXX.
XXXXX

Now if the output above is closely observed, the difference in having a neatly centered triangle is odd rows can only be output. The modulo operator % can help me determine what numbers are odd.

1%2, 2%2, 3%2, 4%2
(1, 0, 1, 0)
for n in range(1,l+1):
    if n%2==1: print('X'*n + '.'*(l-n))
X....
XXX..
XXXXX

To center this triangle, I just have to split the padding on either side.

for n in range(1,l+1):
    padding = (l-n)//2
    if n%2==1: print('.'*padding + 'X'*n + '.'*padding)
..X..
.XXX.
XXXXX

I don’t actually need to use % to determine what number is odd. The third parameter of range lets us define the step.

list(range(1,5,2))
[1, 3]
for n in range(1,l+1,2):
    pad = (l-n)//2
    print(' '*pad + '.'*n + ' '*pad)
  .  
 ... 
.....

Python has built-in ways to justify text. > right aligns, < left aligns, and ^ centers.

print(f'{'haha':>8}\n{'haha':<8}\n{'haha':^8}')
    haha
haha    
  haha  

If I don’t want to use whitespace to justify, Python has the rjust, ljust, and center methods.

print(f'{'haha'.rjust(8,'-')}\n{'haha'.ljust(8,'-')}\n{'haha'.center(8,'-')}')
----haha
haha----
--haha--

Back to the triangle.

for n in range(1,l+1,2): print(f'{'.'*n:^{l}}')
  .  
 ... 
.....

In 1 line.

print('\n'.join(f'{'.'*n:^{l}}' for n in range(1,l+1,2)))
  .  
 ... 
.....

Justifying with another character.

print('\n'.join(f'{('.'*n).center(l, '#')}' for n in range(1,l+1,2)))
##.##
#...#
.....

If you have any comments, questions, suggestions, feedback, criticisms, or corrections, please do post them down in the comment section below!

Back to top