str.center()

str.center(width[, fillchar])
Returns: str · Updated March 13, 2026 · String Methods
strings formatting padding

The center() method returns a new string centered within a field of the specified width. It pads the string on both sides with a fill character (default is a space) until the total width is reached. If the string is longer than the specified width, the original string is returned unchanged.

Syntax

str.center(width[, fillchar])

Parameters

ParameterTypeDefaultDescription
widthintRequiredThe total width of the resulting centered string
fillcharstr" " (space)The character used for padding on both sides

Returns: A new string of the specified width with the original string centered.

Raises: TypeError if fillchar is not a string of exactly one character.

Examples

Basic usage

text = "hello"
print(text.center(10))
#   hello   

The string “hello” (5 characters) is centered in a 10-character field, giving 3 spaces on each side.

Using a custom fill character

# Pad with dashes
text = "Python"
print(text.center(12, "-"))
# ---Python---

# Pad with asterisks
text = "centered"
print(text.center(14, "*"))
# ***centered****

You can use any single character for padding, not just spaces.

Width smaller than string

# If width is less than or equal to string length, returns original
text = "hello"
print(text.center(3))
# hello

When the specified width is smaller than the original string, the original string is returned unchanged.

Visualizing in terminal output

# Creating bordered output
title = "Welcome"
border = "*" * (len(title) + 4)
print(border)
# ************
print(f"* {title} *")
# * Welcome *
print(border)
# ************

# Using center() for the same result
print("*" * 20)
print("Python".center(20, " "))
print("*" * 20)
# ********************
#        Python       
# ********************

Common Patterns

Creating terminal banners

def banner(text, width=40, char="="):
    """Create a centered banner with border characters."""
    return f"{char * width}\n{text.center(width)}\n{char * width}"

print(banner("Hello"))
# ========================================
#                Hello                   
# ========================================

print(banner("Python 3.12", 50, "-"))
# --------------------------------------------------
#                    Python 3.12                    
# --------------------------------------------------

Centering table data

# Simulating a simple table
headers = ["Name", "Age", "City"]
data = [("Alice", "30", "NYC"), ("Bob", "25", "LA")]

col_widths = [10, 5, 8]

# Print header
for header, width in zip(headers, col_widths):
    print(header.center(width), end=" | ")
print()
#   Name    | Age  |  City   

# Print separator
print("-" * 27)
# ---------------------------

# Print rows
for row in data:
    for cell, width in zip(row, col_widths):
        print(cell.center(width), end=" | ")
    print()
#   Alice   |  30  |   NYC   
#    Bob    |  25  |   LA    

Aligning fixed-width data

# Formatted output in scripts
items = ["apple", "banana", "cherry"]
prices = [0.5, 0.75, 1.0]

for item, price in zip(items, prices):
    print(f"{item.center(10)} : ${price:.2f}")
#   apple    : $0.50
#   banana   : $0.75
#   cherry   : $1.00

Errors

  • TypeError: Raised when fillchar is not a string. Python requires the fill character to be a string.
# This raises TypeError
"hello".center(10, 123)
# TypeError: center() argument 2 must be str, not int
  • ValueError: Raised when fillchar is not exactly one character.
# This raises ValueError
"hello".center(10, "ab")
# ValueError: center() argument 2 must be str of length 1

See Also