Content · Programming · Python

Python str.center Method: Usage and Examples

str.center(width, fillchar) pads both sides of a string until the total width is reached. The default padding character is a space; an optional fill character must be exactly one character. A width smaller than the.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.center Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.center(width, fillchar) pads both sides of a string until the total width is reached. The default padding character is a space; an optional fill character must be exactly one character. A width smaller than the existing text does not truncate it.

When You Would Use This


Display a heading between a fixed number of separator characters.

Step-by-Step Example


heading_text = "Report"
print(heading_text.center(12, "-"))
print(heading_text.center(4, "-"))

How the Example Works


The first result is ---Report---; the second remains Report because the requested width is shorter than the text. The result is a new string.

Example Output


---Report---
Report

Try It Yourself


Center "Sales" in a field of 15 characters using dots.

Common Beginner Mistakes


  • Treating width as the number of padding characters on each side.
  • Passing a multi-character filler such as "--".
  • Expecting width to count on-screen character cells for emoji or wide Unicode characters.

Key Takeaways


  • str.center(width, fillchar) pads both sides of a string until the total width is reached.
  • The first result is ---Report---; the second remains Report because the requested width is shorter than the text.
  • Avoid this mistake: Treating width as the number of padding characters on each side.
Share this resourceSend this page to someone who may find it useful.