Back to Blog
Python

Python String Center: Syntax, Behavior, and Edge Cases

python string center: Learn how str.center() works in Python: syntax, fill character behavior, odd-width distribution, edge cases, and practical formatting examples.

pythonstring methodstext formattingstr.centerstring alignment
A Python string centered between equal padding characters, illustrating the str.center() method's symmetric alignment behavior.

The python string center operation is handled by the built-in str.center() method, which returns a string of a specified width with the original content centered between padding characters. The method is part of the str type, so it works on any string literal or variable without importing a module.

Syntax and Parameters

The method signature is:

str.center(width, fillchar=' ')

width is the total length of the returned string. fillchar is the character used for padding on both sides, and it defaults to a single space. If fillchar is provided, it must be exactly one character; passing a longer string raises TypeError.

text = "Python" print(text.center(10)) # Output: " Python "

The result has a length of 10. The original string occupies positions 2 through 7, with two spaces on each side.

How Centering Distributes Odd Widths

When the difference between width and the original string length is odd, the extra padding character goes to the right side. This is not a bug; it is the documented behavior.

text = "abc" print(text.center(6)) # Output: " abc "

The difference is 3, so the left side receives 1 space and the right side receives 2. If you need the extra character on the left instead, you can compute the padding manually:

def center_left(text, width, fillchar=' '): total = width - len(text) if total <= 0: return text left = total // 2 right = total - left return fillchar * left + text + fillchar * right

This is rarely necessary, but it matters when aligning columns in terminal output where the visual offset must match a specific convention.

Using a Custom Fill Character

The second parameter allows any single character as padding. This is useful for visual separators, comment blocks, or log formatting.

print(" Section ".center(30, "=")) # Output: "============ Section ============"

The fill character must be exactly one character. A common mistake is passing a multi-character string:

try: "text".center(10, "--") except TypeError as e: print(e) # Output: The fill character must be exactly one character long

Edge Cases: Width Smaller Than or Equal to the String Length

When width is less than or equal to len(text), center() returns the original string unchanged. No padding is added, and no truncation occurs.

text = "Python" print(text.center(3)) # Output: "Python" print(text.center(6)) # Output: "Python"

This behavior is important when building dynamic layouts: if the content length varies, centering it into a fixed width can produce inconsistent alignment because longer strings are returned as-is. If truncation is required, you must handle it separately, for example with slicing:

def centered_truncated(text, width, fillchar=' '): if len(text) >= width: return text[:width] return text.center(width, fillchar)

Interaction with Multibyte Characters

The width parameter counts code points, not display columns. For strings containing CJK characters, emoji, or combining marks, the visual width of the centered result may not match the requested width in a terminal or monospace font.

text = "東京" print(text.center(8)) # Output: " 東京 "

The string has 2 code points, so the result has length 8. But each CJK character typically occupies two terminal columns, so the visual result is wider than 8 columns. If you are building terminal UI tables with mixed-language content, consider using a display-width library such as wcwidth instead of relying on center() alone.

Comparison with ljust() and rjust()

The str type provides three alignment methods: ljust(), rjust(), and center(). They share the same width and fillchar parameters and the same rule for handling widths smaller than the string length.

MethodPadding placementUse case
ljust()Right sideLeft-aligned columns in reports
rjust()Left sideRight-aligned numbers in tables
center()Both sidesHeaders, titles, visual separators

Choosing between them depends on the visual alignment you need. center() is rarely the right choice for numeric columns because numbers are usually right-aligned for readability.

Performance Characteristics

center() creates a new string on every call. The operation is O(width) because the padding characters and the original content are copied into the result. For a one-off formatting call, this cost is negligible. If you are centering thousands of strings in a loop, the allocation overhead is the same as any other string concatenation, so there is no special performance trap.

The main performance concern is not the method itself but how it is used. Calling center() inside a tight loop with a large width repeatedly allocates large strings. If the same centered result is needed multiple times, compute it once and reuse the value.

header = " Report ".center(40, "=") for line in data: output.write(header + "\n")

This avoids recomputing the same centered string for every line.

Compatibility and Version Behavior

str.center() has existed since Python 2 and behaves identically in Python 3. The fillchar parameter has always required a single character. No version-specific behavior needs to be handled in modern Python code. The method also works on bytes objects in Python 3, with the same semantics, but the fill byte must be a bytes object of length 1.

b"data".center(10, b"-") # Output: b"---data---"

This can be useful when writing binary protocols that require fixed-width fields, though most text protocols are better served by the string version.

python string center: Practical Usage and Code Examples | RYUSLOG DEV