What Is the center() Method in Python?
The center() method in Python is a built-in string function used to align text in the middle of a given width.
If there’s extra space on either side, Python automatically fills it with spaces or a custom character you choose.
This method is especially useful when formatting console outputs, creating headers, or aligning columns in text-based tables.
Purpose of center() Method
It’s often used in text-based UI designs, tables, and formatted reports where neat alignment matters.
The main goals of the center() method are:
- To visually align a string in the center of a specified field width.
- To add padding using spaces or a custom fill character.
- To make printed outputs or logs look cleaner and more structured.
It’s often used in text-based UI designs, tables, and formatted reports where neat alignment matters..
Syntax of center()
string.center(width, fillchar)
Quick Example
text = “Python” result = text.center(10, “-“) print(result) print(word1.casefold() == word2.casefold()) # True # Output:–Python–