my_str="plus2net.com"
print(my_str.center(30))
Output is here ( there are blank spaces at both sides of the string. Total length of the output string is equal to 30)
plus2net.com
my_str="plus2net.com"
print(my_str.center(30,'*'))
Output
*********plus2net.com*********
Syntax
center(length,filling_char)
length: required , the length of the string after adding filling_char at both sides. The `center()` method can be particularly useful for formatting console outputs, such as headers or titles.
my_str = "Welcome"
print(my_str.center(50, "-"))
-------------------Welcome-------------------
When displaying tabular data, you can use `center()` to align column headers consistently, enhancing readability.
headers = ["ID", "Name", "Marks"]
for header in headers:
print(header.center(15, " "), end="")
ID Name Marks
We can create a dynamic function to center various strings with different padding lengths.
def display_centered(text, width, char=" "):
print(text.center(width, char))
display_centered("Plus2net", 40, "*")
display_centered("Python String Methods", 50, "-")
**************Plus2net**************
---------Python String Methods---------
In a web-based application, you can use `center()` to display consistent headers, even when displayed across various screen sizes.
title = "Dashboard"
print(title.center(30, "="))
========Dashboard========