Python Strings: center()

center() pads out a string so that the original string is in the center. The default padding is a space and you can optionally define the pad-character. Remember, strings are immutable so the original string is not altered but a copy returned.

Syntax 
center(width, {pad-character})
– width is the length you want the new string to be.
if this is less than or equal to the length of the original then no change will occur.
– pad-character is an optional character
this must be one character only!
the default is whitespace

# example
# open your favourite Python editor and use the interactive window

>>> my_string = "center"
>>> my_string.center(10)
'  center  '

This has added 4 spaces to a copy of the string, 2 spaces at either end.

NOTE: center() pads from the left first, then right, then left and so on, so if there are an uneven number of paddings the left side will contain the extra padding.

>>> my_string.center(9, "-")
'--center-'

The original string remains unaltered

>>> print my_string
center

Assign the centered string to a new variable…

>>> my_new_string = my_string.center(12, "~")
>>> print my_new_string
~~~center~~~

or overwrite the original…

>>> my_string = my_string.center(14, "*")
>>> print my_string
****center****

Previous: capitalize()
Next: count()

 

Notes:
– pads out a string with a user defined character on the left and right of the original string
– takes one required parameter, the length the new string should be as an integer
the original string will sit in the center surrounded by whitespace (deafult)
– takes on optional parameter, the character to pad out the string with
the original string will sit in the center surrounded by the character on each side
– optional parameter must be a single character string
– if the required parameter is less than or equal to the original string no padding will occur and the copy will match the original string.
– pads from the left first, then right, then left meaning that the left side can contain one more character padding than the right.
– does not alter the original string