Python center() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The center() method returns a new string with the original text centered inside a field of a specified width. Padding is added on both sides—using spaces by default, or any single character you choose. It is a simple way to format headers, console output, and fixed-width columns.

01

Center Align

Place text in the middle.

02

Width Parameter

Set total string length.

03

fillchar

Custom padding character.

04

Immutable

Original string stays unchanged.

05

Headers

Format titles and banners.

06

vs ljust/rjust

Pick the right alignment.

Definition and Usage

In Python, center() is a built-in string method that pads the string on the left and right so the original text sits in the middle of a field with total length width. For example, "Python".center(10, "*") returns "**Python**"— two asterisks on each side to reach a total width of 10 characters.

💡
Beginner Tip

Think of width as the total size of the final string, not the amount of padding to add. If the text is already longer than width, Python returns the original string with no changes.

📝 Syntax

The center() method accepts one required and one optional parameter:

python
string.center(width, fillchar)

Syntax Rules

  • width — the total length of the returned string (required, integer).
  • fillchar — optional single character used for padding; defaults to a space (" ").
  • Return value — a new str; the original is never modified.
  • Width too small — if width <= len(string), the original string is returned unchanged.
  • Odd padding — when extra space does not split evenly, the left side gets one extra character.

⚡ Quick Reference

ExpressionResult
"Python".center(10, "*")"**Python**"
"Hi".center(6)" Hi " (spaces)
"Hello".center(3)"Hello" (unchanged)
"A".center(4, "-")"-A--"
"".center(5, ".")"....."
Basic
"title".center(20, "-")

Centered banner line

Default pad
"data".center(10)

Space padding

Column
name.center(15)

Fixed-width field

Length
len("Hi".center(8))

Returns 8

Examples Gallery

Run these examples in any Python 3 interpreter. Each one shows a common center-alignment pattern.

📚 Getting Started

Start with a short word and pad it to a fixed width using a custom fill character.

Example 1 — Basic center() with fillchar

Center "Python" inside a field of 10 characters, using asterisks as padding.

python
original = "Python"
centered = original.center(10, "*")

print("Original:", original)
print("Centered:", centered)
print("Length:  ", len(centered))

How It Works

  • "Python" is 6 characters; width is 10, so 4 padding characters are needed.
  • Python splits padding evenly: 2 on the left, 2 on the right.
  • original is unchanged; centered is a new string.

Example 2 — Default Space Padding

When you omit fillchar, Python pads with spaces.

python
text = "Hi"
padded = text.center(8)

print(repr(padded))
print(len(padded))

How It Works

repr() makes the spaces visible. Three spaces on each side plus "Hi" (2 chars) gives a total length of 8.

📈 Practical Patterns

Real-world formatting for console output, banners, and aligned columns.

Example 3 — Centered Header Banner

Create a decorative title line for terminal or log output.

python
title = "Welcome to Python"
banner = title.center(30, "-")

print(banner)

How It Works

The title is 17 characters; 13 dashes are added total. Because 13 is odd, the left side gets 7 dashes and the right gets 6.

Example 4 — Fixed-Width Table Column

Center values inside a column for readable tabular output.

python
scores = ["92", "100", "87", "95"]

print(" Score ")
print("-" * 7)
for score in scores:
    print(score.center(7))

How It Works

Each score is centered in a 7-character-wide column. Shorter values like "92" get more padding; "100" gets less.

Example 5 — center() vs ljust() vs rjust()

See how the three alignment methods place the same text differently.

python
word = "Data"
width = 12

print("center:", repr(word.center(width, ".")))
print("ljust: ", repr(word.ljust(width, ".")))
print("rjust: ", repr(word.rjust(width, ".")))

How It Works

  • center() splits padding on both sides.
  • ljust() keeps text on the left and pads the right.
  • rjust() keeps text on the right and pads the left.

🚀 Common Use Cases

  • Console banners — center titles and section headers with dash or star padding.
  • Report columns — align numeric or short text values in fixed-width fields.
  • Receipt formatting — center store names or headings on printed lines.
  • CLI menus — highlight the active menu title in the middle of the screen width.
  • Debug output — visually separate log sections with centered divider lines.

🧠 How center() Works

1

Python checks the width

If width is not larger than the string length, the original string is returned as-is.

Guard
2

Padding is calculated

Python computes how many fillchar characters are needed and splits them between left and right sides.

Pad
3

A new string is built

Left padding + original text + right padding are joined into one string of exactly width characters.

Build
=

Centered output

Text sits in the middle of a fixed-width field, ready to print or display.

📝 Notes

  • fillchar must be exactly one character. Passing "--" raises TypeError.
  • When padding does not divide evenly, the extra character goes on the left side.
  • center() counts string length in characters, not display width—emoji and some Unicode may appear wider in terminals.
  • For left or right alignment instead, use ljust() or rjust().

Conclusion

The center() method is a straightforward way to center-align text in Python. With just a width and an optional fill character, you can format headers, columns, and banners without manual space counting or string concatenation.

Remember: width is the total size of the result, padding splits left and right, and if the text is already long enough, nothing changes.

💡 Best Practices

✅ Do

  • Pick a width that fits your column or screen layout
  • Use a visible fillchar like "-" for banners
  • Use repr() when debugging to see hidden spaces
  • Combine with strip() before centering user input
  • Compare ljust() and rjust() when center is not needed

❌ Don’t

  • Pass a multi-character string as fillchar
  • Assume width means “padding amount” only
  • Expect the original string to change in place
  • Use center() for complex table layouts—consider formatted printing
  • Forget that odd padding adds an extra character on the left

Key Takeaways

Knowledge Unlocked

Five things to remember about center()

Use these points when formatting aligned text in Python.

5
Core concepts
🔢 02

width Param

Total result length.

Syntax
03

fillchar

One pad character.

Optional
📄 04

Banners

Great for headers.

Use case
05

Too Narrow

No change if too short.

Edge case

❓ Frequently Asked Questions

center() returns a new string with the original text centered inside a field of a given width. Extra space on the left and right is filled with a padding character, which defaults to a space.
string.center(width, fillchar). width is required and sets the total length of the returned string. fillchar is optional and defaults to a single space character.
If width is less than or equal to the length of the original string, center() returns the original string unchanged. No padding is added.
fillchar must be exactly one character—a letter, digit, symbol, or space. For example, "-" or "*". Passing a multi-character string raises TypeError.
No. Python strings are immutable. center() always returns a new string; the original stays the same.
center() adds padding on both sides so the text sits in the middle. ljust() pads on the right (left-aligned), and rjust() pads on the left (right-aligned).

Explore More Python String Methods

Continue with count(), encode(), and the rest of the string method reference.

Next: count() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful