center(): centered string in Python

Use the center() method to center a string.

word = 'beach'
number_spaces = 32

word_centered = word.center(number_spaces)

print(word)
#'beach'

print(word_centered)
##output: '              beach              '

Notice the spaces in the second string. The word ‘beach’ has 5 characters, which gives us 28 spaces to fill with empty space, 14 spaces before and 14 after to center the word.

The original word variable remains unchanged, thus we need to assign the return of the method to a new variable, word_centered in this case.

The center() also accepts a specific character as a parameter to fill the remaining space.

word = 'beach'
number_chars = 33
char = '$'

word_centered = word.center(number_chars, char)

print(word)
#beach

print(word_centered)
#output: $$$$$$$$$$$$$$beach$$$$$$$$$$$$$$

Similar to the first situation, I have 14 $ in each side to make it 33 total when I count the 5 chars contained in the word ‘beach’.