Published on

Blank filling issue with `center()` function

Authors
  • avatar
    Name
    hwahyeon
    Twitter

While solving an algorithm problem, I used the center() function to center-align characters, but I kept getting the wrong answer. It turned out that the center() function fills the space with blanks while centering, which caused the issue.

For example, in a problem where you need to print a tree made of *:

1

n = 5
for i in range(1, n + 1):
    stars = '*' * (2 * i)
    print(stars.center(n * 2))
    **
   ****
  ******
 ********
**********

2

n = 5
for i in range(1, n + 1):
    spaces = ' ' * (n - i)
    stars = '*' * (2 * i)
    print(spaces + stars)
    **
   ****
  ******
 ********
**********

They look the same, but they are not. Let's check.

n = 5

for i in range(1, n + 1):
    stars = '*' * (2 * i)
    centered = stars.center(n * 2)
    print(f"Length: {len(centered)}")

print("----------")

for i in range(1, n + 1):
    spaces = ' ' * (n - i)
    stars = '*' * (2 * i)
    manual_spacing = spaces + stars
    print(f"Length: {len(manual_spacing)}")
Length: 10
Length: 10
Length: 10
Length: 10
Length: 10
----------
Length: 6
Length: 7
Length: 8
Length: 9
Length: 10