The str.center(width[, fillchar]) method returns a copy of the string centered within a field of the specified width, using fillchar (defaulting to an ASCII space) as padding.
The Odd-Margin Distribution Rule: When the required total padding (width - len(s)) is an odd integer, Python splits the margins deterministically: the left side receives (width - len(s)) // 2 characters, while the right side receives the extra remaining character. If width ≤ len(s), the original string is returned unaltered without truncation.
The formal method signature defined in Python's standard library is:
str.center(width, fillchar=' ', /)
| Parameter | Type | Default | Description |
|---|---|---|---|
width |
int |
Required | The target total field width. If width is less than or equal to the string length, Python returns the original string without truncation. |
fillchar |
str |
' ' |
Optional. A single character string used for margin padding. Passing an empty string or a multi-character string raises a TypeError. |
center() allocates and returns a new string. The calling string variable remains unaltered.
By default, center() inserts space characters symmetrically on both sides of the string:
title = "plus2net.com"
# Centers within a 20-character field
centered = title.center(20)
print("Original: ", repr(title))
print("Centered: ", repr(centered))
print("Length: ", len(centered))
Expected Output:
Original: 'plus2net.com'
Centered: ' plus2net.com '
Length: 20
When width ≤ len(s), Python performs zero padding and returns the full string without altering content:
word = "Enterprise Architecture"
print(word.center(10)) # Returns 'Enterprise Architecture' (len 23)
A crucial implementation detail in CPython occurs when the number of padding characters needed is an odd number:
# Even padding: 3 chars in 'cat', target width 7 -> 4 padding chars
# 2 chars on left, 2 chars on right
print("Even padding: ", repr("cat".center(7, "-")))
# Odd padding: 3 chars in 'cat', target width 6 -> 3 padding chars
# 1 char on left (3 // 2), 2 chars on right (remainder)
print("Odd padding: ", repr("cat".center(6, "-")))
Expected Output:
Even padding: '--cat--'
Odd padding: '-cat--'
left_pad = (width - len(s)) // 2
right_pad = (width - len(s)) - left_pad
Supplying a custom single character for fillchar allows formatting decorative terminal banners, visual dividers, and tabular summaries:
header = " SYSTEM REBOOT "
print(header.center(30, "="))
print(header.center(30, "*"))
print(header.center(30, "~"))
Expected Output:
======= SYSTEM REBOOT ========
******* SYSTEM REBOOT ********
~~~~~~~ SYSTEM REBOOT ~~~~~~~~
Python provides a dedicated quartet of alignment tools across string methods and f-string format specifications:
| Alignment Direction | String Method | Equivalent f-String Format | Example on "DATA" (width=8, fill='-') |
|---|---|---|---|
| Center | str.center(width, fill) |
f"{s:{fill}^{width}}" |
"--DATA--" |
| Left Justify | str.ljust(width, fill) |
f"{s:{fill}<{width}}" |
"DATA----" |
| Right Justify | str.rjust(width, fill) |
f"{s:{fill}>{width}}" |
"----DATA" |
Constructing uniform visual headers for CLI scripts, cron jobs, and deploy logs:
def print_cli_banner(title: str, total_width: int = 50, border_char: str = "=") -> str:
padded_title = f" {title.upper()} "
return padded_title.center(total_width, border_char)
print(print_cli_banner("database migration"))
print(print_cli_banner("running smoke tests"))
print(print_cli_banner("deployment complete"))
Expected Output:
=============== DATABASE MIGRATION ===============
============== RUNNING SMOKE TESTS ===============
============== DEPLOYMENT COMPLETE ===============
Formatting receipt line items and category headers for POS printers or text summaries:
def format_receipt_header(category: str, line_width: int = 36) -> str:
return category.center(line_width, "-")
print(format_receipt_header(" ORDER SUMMARY "))
print(format_receipt_header(" PAYMENT DETAILS "))
Expected Output:
----------- ORDER SUMMARY -----------
---------- PAYMENT DETAILS ----------
Generating text tables with perfectly centered column contents:
def format_table_row(cols: list[str], widths: list[int]) -> str:
cells = [str(col).center(w) for col, w in zip(cols, widths)]
return "|" + "|".join(cells) + "|"
headers = ["ID", "Service", "Status"]
col_widths = [8, 16, 12]
print(format_table_row(headers, col_widths))
print(format_table_row(["101", "Auth API", "ONLINE"], col_widths))
print(format_table_row(["102", "Payment Gateway", "HEALTHY"], col_widths))
Expected Output:
| ID | Service | Status |
| 101 | Auth API | ONLINE |
| 102 |Payment Gateway | HEALTHY |
Centering an entire block of multiline text line-by-line while computing the maximum paragraph width automatically:
def center_multiline_block(text: str, total_width: int = 50) -> str:
lines = text.splitlines()
return "\n".join(line.strip().center(total_width) for line in lines)
poem = """Roses are red,
Violets are blue,
Python is powerful,
And clean to write too."""
print(center_multiline_block(poem, 40))
Expected Output:
Roses are red,
Violets are blue,
Python is powerful,
And clean to write too.
Passing a multi-character string like "--" or an empty string "" to fillchar raises an immediate exception:
# TypeError: The fill character must be exactly one character long
"text".center(10, "--")
# Valid single character strings:
"text".center(10, "-")
"text".center(10, " ")
Calling "TITLE".center(20, "=") produces "=======TITLE========" without spaces around TITLE. If you want spacing, include spaces in the target string: f" {title} ".center(20, "=").
Below is a production-grade utility class, TextCenterer, demonstrating CLI banner generation, table cell centering, and automated unit assertions:
class TextCenterer:
@staticmethod
def make_banner(title: str, width: int = 40, border: str = "=") -> str:
"""Formats a bordered banner with spaces around title."""
padded = f" {title.strip()} "
return padded.center(width, border)
@staticmethod
def center_cell(content: str, column_width: int) -> str:
"""Centers text within a table column."""
return content.center(column_width)
# ==========================================
# SELF-CHECKING UNIT ASSERTIONS
# ==========================================
centerer = TextCenterer()
# 1. Basic space centering
assert "test".center(8) == " test "
assert "test".center(4) == "test"
assert "test".center(2) == "test" # No truncation
# 2. Odd-padding asymmetry check (extra char on right)
assert "cat".center(6, "-") == "-cat--"
assert "cat".center(7, "-") == "--cat--"
# 3. Custom fillchar
assert "ABC".center(9, "*") == "***ABC***"
# 4. Banner generation
banner = centerer.make_banner("READY", 20, "=")
assert banner == "====== READY ======="
assert len(banner) == 20
# 5. TypeError validation on invalid fillchar length
try:
"test".center(10, "---")
assert False, "Expected TypeError not raised"
except TypeError as e:
assert "must be exactly one character" in str(e)
print("Centered text: ", repr("plus2net".center(16)))
print("Banner generated:", banner)
print("Odd margin test: ", repr("A".center(4, ".")))
print("All str.center() unit assertions passed successfully!")
Open in Google Colab View on GitHub
Run all text centering examples interactively, explore odd/even padding margins, construct ASCII table layouts, and test fill character rules in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.