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
| Parameter | Description |
|---|---|
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
print("[" + "menu".center(10) + "]")
print("menu".center(12, "*"))
Output
[ menu ] ****menu****
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.ljust()· Return the string left-justified in a field of the given width, padded on the right with a fill character.str.rjust()· Return the string right-justified in a field of the given width, padded on the left with a fill character.str.zfill()· Return the string padded on the left with zeros to the given width, keeping a leading + or - sign in front.str.format()· Return a formatted string, filling {} placeholders with the arguments. f-strings are usually simpler.- Python Strings · tutorial