Python str.center() function
In Python, the str.center()
method is used to center-align a string within a specified width, padding it with a specified character (space by default) on both sides. This method is useful for formatting strings in a way that they appear centered in a given space, which can be helpful for console output or text alignment in various applications.
Syntax
- width: The total width of the resulting string after padding. If this value is less than the length of the original string, the original string is returned unchanged.
- fillchar (optional): The character to use for padding the string. This must be a single character. The default is a space (
' '
).
Example Usage
- Basic usage with default padding (spaces):
- Using a custom fill character:
- Width less than the original string:
If the specified width is less than the length of the original string, the original string is returned unchanged:
- Centering with odd and even widths:
The center()
method distributes the padding evenly. If the total width is odd, the extra space is added to the right:
- Empty string:
If an empty string is passed, the result will also be an empty string regardless of the specified width:
Summary
- Use
str.center()
to center-align a string within a specified width. - It allows for customizable padding using a fill character, defaulting to a space if none is specified.
- If the specified width is less than the length of the string, the original string is returned without modification.
- This method is useful for formatting output in console applications or any scenario where text alignment is important.