Python 3 reference · String Methods

Python String center() Method

Return the string centred in a field of the given width, padded on both sides with a fill character (a space by default).

Python 3 Since 3.0

Syntax

str.center(width, fillchar=' ')

Parameters

ParameterDescription
width Total length of the result.
fillchar optional A single padding character. Default: ' '

Return value

A new string (unchanged if width is not larger than the string).

Examples

Centre textTry it yourself
print("[" + "menu".center(10) + "]")
print("menu".center(12, "*"))

Output

[   menu   ]
****menu****
A simple tableTry it yourself
for word in ["Tea", "Coffee"]:
    print("|" + word.center(10, ".") + "|")

Output

|...Tea....|
|..Coffee..|

For formatted output, f"{text:^10}" does the same inside an f-string.

Version history

VersionChange
Python 3.0Added