YouTip LogoYouTip

Att String Center

## Python String center() Method The `center()` method returns a new string padded with a specified fill character (defaults to an ASCII space) so that the original string is centered within a total field width. --- ## Syntax ```python str.center(width[, fillchar]) ``` ### Parameters * **`width`**: The total width of the resulting string. If `width` is less than or equal to the length of the original string (`len(str)`), the original string is returned unmodified. * **`fillchar`** *(Optional)*: The padding character used to fill the remaining space. It must be a single character (string of length 1). The default value is an ASCII space `' '`. ### Return Value This method returns a new, centered string of length `width` padded with `fillchar`. The original string remains unchanged. --- ## Code Examples ### Example 1: Basic Usage with Default Padding If you do not provide the `fillchar` argument, the method defaults to using spaces. ```python # Define the original string text = "YouTip" # Center the string within a width of 20 using default space padding result = text.center(20) print(f"'{result}'") # Output: ' YouTip ' ``` ### Example 2: Using a Custom Fill Character You can specify a custom character, such as an asterisk `*` or a hyphen `-`, to pad the string. ```python text = "YouTip" # Center the string within a width of 20 using '*' as the fill character result = text.center(20, '*') print(result) # Output: *******YouTip******* ``` ### Example 3: Handling Odd Padding Spaces When the required padding cannot be divided equally on both sides, Python places the extra padding character on the right side. ```python text = "code" # Length is 4 # We want a total width of 7. # Total padding needed = 7 - 4 = 3 characters. # Python will place 1 character on the left and 2 on the right. result = text.center(7, '-') print(result) # Output: -code-- ``` --- ## Considerations & Edge Cases ### 1. Width is Less Than or Equal to String Length If the specified `width` is smaller than or equal to the length of the original string, Python will return the original string without truncating it or adding any padding. ```python text = "YouTip" print(text.center(4, '*')) # Output: YouTip ``` ### 2. `fillchar` Must Be a Single Character The `fillchar` argument must be exactly one character long. Passing an empty string or a string with multiple characters will raise a `TypeError`. ```python text = "YouTip" try: # This will raise an error because the fillchar length is not 1 text.center(20, 'xyz') except TypeError as e: print(f"Error: {e}") # Output: Error: The fill character must be exactly one character long ```
← Att String CountAtt String Capitalize β†’