Python String center()
Method
The center() method in Python returns a new string of a given length with the original string center-aligned, and padded with spaces or a specified fill character on both sides.
Syntax
string.center(width, fillchar=' ')
Parameters:
width
– Total length of the final string (including the original string and padding)fillchar
(optional) – The character used for padding (default is space)
Returns:
- A new centered string of specified width
Example 1: Center a String with Spaces
text = "Python"
centered = text.center(10)
print(centered)
Python
Why? The original string is 6 characters long. To make it 10 characters wide, 2 spaces are added to each side.
Example 2: Center a String with Custom Character
text = "Python"
centered = text.center(12, '*')
print(centered)
***Python***
Note: If the number of padding characters is odd, the extra character is placed on the right side.
Use Case: Formatting Output
Centering is often used when displaying titles or headers in reports or CLI tools.
title = "Welcome"
print(title.center(30, '='))
===========Welcome===========
Common Mistakes
- Using a multi-character string for
fillchar
will raise aTypeError
- Passing a non-integer value for
width
will also raise an error
Interview Tip
If asked to format text output in coding interviews, methods like center()
, ljust()
, and rjust()
are great tools to mention.
Summary
center()
centers a string in a field of a given width- Spaces are used for padding by default, but you can specify a different character
- Useful for text formatting in CLI or reports
Practice Problem
Write a program that takes a user's name and displays it centered within a line of asterisks:
name = input("Enter your name: ")
print(name.center(30, '*'))