Python String center()

Python String center() method is a built-in function used to align the string to the center by filling the paddings to the left and right of the string with a specified fillchar(default fill character is an ASCII space). 

Syntax

The syntax of center() method is:

string.center(width[, fillchar])

Parameter

The center() function takes 2 parameters.

  • width – length of the string with padded characters
  • fillchar (optional) – Character which needs to be padded. If not provided, space is used as the default character.

Return Value

The center() function returns a string padded with a specified fillchar. It doesn’t modify the original string.

The original string is returned if the width is less than or equal to len(s)

Example 1: center() Method With default fillchar

text = "Python Rocks"

# Defaults fills with space on both sides of string
new_text = text.center(20)

print("Original String:", text)
print("Centered String:", new_text)

Output

Original String: Python Rocks
Centered String:     Python Rocks    

Example 2: center() Method With * fillchar

text = "Python Rocks"

# Defaults fills with * on both sides of string
new_text = text.center(20, "*")

print("Original String:", text)
print("Centered String:", new_text)

Output

Original String: Python Rocks
Centered String: ****Python Rocks****

Example 3: Returns an original string if the width is less than the length of the string

In this example, the width specified is 10 and the length of the string is 12. Hence the center() method returns the original string as-is without any padding characters.

text = "Python Rocks"

# width is less then length of string
new_text = text.center(10, "*")

print("Length of string:", len(text))
print("Original String:", text)
print("Centered String:", new_text)

Output

Length of string: 12
Original String: Python Rocks
Centered String: Python Rocks
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like