A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-string-center-method/ below:

Python String center() Method - GeeksforGeeks

Python String center() Method

Last Updated : 28 Apr, 2025

center() method in Python is a simple and efficient way to center-align strings within a given width. By default, it uses spaces to fill the extra space but can also be customized to use any character we want. Example:

Python
s1 = "hello"
s2 = s1.center(20)

print(s2)

Explanation: Here, the word "hello" is centered within a 20-character wide space, with spaces padded on both sides.

Syntax of string center()

string.center(length[, fillchar])

Parameters:

Returns: It returns a string padded with specified fillchar and it doesn't modify the original string.

Examples of string center() parameter

Example 1: The center() method allows you to customize the character used to fill the padding by passing the fillchar argument. This is useful when formatting text with visual markers like dashes (-) or asterisks (*).

Python
a = "hello"
b = a.center(20, '-')

print(b)

Output
-------hello--------

Explanation: Here, the string "hello" is centered within 20 characters using dashes (-) as the padding character.

Example 2: If the width specified in the center() method is smaller than the length of the original string, Python will not change the string. It will simply return the original string without any centering.

Python
a = "hello"
b = a.center(3)

print(b)

Explanation: In this case, since the width (3) is less than the string length (5), no padding is applied.

Example 3: center() is often used to format headers in console-based tables, making them more readable and visually distinct.

Python
h1 = "Name"
h2 = "Age"
h3 = "Location"

s1 = h1.center(20, '-')
s2 = h2.center(20, '-')
s3 = h3.center(20, '-')

print(s1)
print(s2)
print(s3)

Output
--------Name--------
--------Age---------
------Location------

Explanation: Here, the headers are centered and the extra space is filled with dashes (-). This gives the headers a clean and organized look when printed.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4