center(): Adding chars to both side of the string.

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         

With filling_char

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.
filling_char : (optional), default is blank space, used at both sides of the string.

Example: Centering Text for Console Output

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-------------------
  

Use Case: Creating Table Headers

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     
  

Advanced Example: Centering Multiple Strings Dynamically

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---------
  

Example: Using `center()` to Format Titles in a Web Application

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========
  


All String methods


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer