Python String center() Method

The center() method in Python is used to center align a string within a specified width. This method pads the string with specified characters (by default, spaces) to ensure that the string is centered.

Table of Contents

  1. Introduction
  2. center() Method Syntax
  3. Understanding center()
  4. Examples
    • Basic Usage
    • Using center() with Different Fill Characters
  5. Real-World Use Case
  6. Conclusion

Introduction

The center() method allows you to align a string in the center within a specified width. This is particularly useful for creating formatted output where text needs to be displayed in a visually appealing manner.

center() Method Syntax

The syntax for the center() method is as follows:

str.center(width[, fillchar])

Parameters:

  • width: The total width of the resulting string. The original string will be centered within this width.
  • fillchar (optional): The character to fill the padding with. Default is a space.

Returns:

  • A new string of specified width with the original string centered and padded with the fill character.

Understanding center()

The center() method creates a new string of the specified width, with the original string centered and any extra space filled with the specified fill character. If the total width is less than the length of the original string, no padding is added, and the original string is returned.

Examples

Basic Usage

To demonstrate the basic usage of center(), we will center a string within a specified width and print it.

Example

text = "Namaste"
centered_text = text.center(20)
print("Centered text:", centered_text)

Output:

Centered text:       Namaste       

Using center() with Different Fill Characters

This example shows how to use the center() method with a different fill character.

Example

text = "Namaste"
centered_text = text.center(20, '*')
print("Centered text with '*':", centered_text)

Output:

Centered text with '*': ******Namaste*******

Real-World Use Case

Creating a Title for a Report

In real-world applications, the center() method can be used to create a title for a report or a section header, ensuring that the title is centered and visually appealing.

Example

def create_title(title):
    return title.center(50, '-')

report_title = "Monthly Report"
formatted_title = create_title(report_title)
print(formatted_title)

Output:

------------------Monthly Report------------------

Conclusion

The center() method in Python is useful for centering strings within a specified width. By using this method, you can create well-formatted and visually appealing text outputs in your Python applications.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare