0
0
PythonHow-ToBeginner · 3 min read

How to Center a String in Python: Simple Guide

To center a string in Python, use the str.center(width, fillchar) method, where width is the total length of the resulting string and fillchar is the optional character to fill the sides. This method returns a new string padded with the fill character to center the original string.
📐

Syntax

The str.center() method has this syntax:

  • width: The total length of the new string after centering.
  • fillchar (optional): The character used to fill the space on both sides. Defaults to a space.

The method returns a new string with the original string centered and padded with the fill character.

python
centered_string = original_string.center(width, fillchar=' ')
💻

Example

This example shows how to center the word "hello" in a string of length 11 using spaces and then using asterisk (*) as the fill character.

python
text = "hello"
centered_with_spaces = text.center(11)
centered_with_asterisks = text.center(11, '*')
print(f"'{centered_with_spaces}'")
print(f"'{centered_with_asterisks}'")
Output
' hello ' '***hello***'
⚠️

Common Pitfalls

One common mistake is forgetting that str.center() returns a new string and does not modify the original string. Another is using a width smaller than the string length, which returns the original string unchanged.

Also, the fillchar must be exactly one character; otherwise, Python raises a TypeError.

python
text = "hello"
# Wrong: expecting original string to change
text.center(11)
print(text)  # prints 'hello', original unchanged

# Right: assign the result
text = text.center(11)
print(text)  # prints '   hello   '

# Wrong: fillchar longer than one character
# text.center(11, '**')  # Raises TypeError
Output
hello hello
📊

Quick Reference

Remember these tips when centering strings in Python:

  • str.center(width) pads with spaces by default.
  • Specify fillchar to use other characters.
  • Returns a new string; original string stays the same.
  • If width is less than string length, original string is returned.
  • fillchar must be a single character.

Key Takeaways

Use str.center(width, fillchar) to center strings with optional padding.
The method returns a new string; it does not change the original string.
If width is smaller than the string length, the original string is returned.
The fillchar must be a single character or it raises an error.
Default padding is spaces if fillchar is not specified.