Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.center() method

Reference for Python str.center(): center a string in a field of a given width with an optional fill character, and how odd padding is split.

The str.center() method returns a string of a given width with the original text in the middle, padded on both sides with spaces or with a fill character you choose. If the width is not larger than the length of the string, you get the string back unchanged.

It is handy for text banners, headings in terminal output and simple tables. For more complex alignment, a format specification such as f"{text:^20}" does the same job.

Python
print("title".center(11, "*"))   # ***title***

Try it

Python Centering text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Same result with a format spec

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.center(width)
str.center(width, fillchar)
Name Description
width The minimum length of the result, as an int.
fillchar Optional. A string of exactly one character used for padding. The default is a space.

Return value: a new str of length max(width, len(s)).

Raises: TypeError if fillchar is not exactly one character long or width is not an integer.

Usage notes

  • Never truncates. When width is less than or equal to len(s), the original string is returned (or an equal copy).
  • Odd padding. When the padding cannot be split evenly, the extra character lands on a side that depends on the string length and width, not always on the right. Do not rely on one side if exact alignment matters; the examples above show both cases.
  • Single fill character. "x".center(5, "ab") raises TypeError. Build wider patterns with string repetition.
  • Counts code points, not display width. East Asian wide characters and emoji take more room on screen than len() suggests, so columns may look uneven.
  • Siblings. ljust() pads on the right and rjust() pads on the left; zfill() pads numbers with zeros.
  • Format spec alternative. f"{s:^{width}}" centers too and is handy inside f-strings.