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

str.center(width, fillchar=' ')
  • 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

  1. Basic usage with default padding (spaces):
text = "Hello" result = text.center(10) print(result) # Output: " Hello "
  1. Using a custom fill character:
text = "Hello" result = text.center(10, '*') print(result) # Output: "**Hello***"
  1. 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:

text = "Hello, World!" result = text.center(5) print(result) # Output: "Hello, World!" (unchanged)
  1. 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:

text = "Hi" result_odd = text.center(5) # width is odd result_even = text.center(6) # width is even print(result_odd) # Output: " Hi " print(result_even) # Output: " Hi "
  1. Empty string:

If an empty string is passed, the result will also be an empty string regardless of the specified width:

text = "" result = text.center(10) print(result) # Output: " " (10 spaces)

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.