Python String center() Method Tutorial

In this section, we will learn what String center() method is and how to use it in Python.

What is String center() Method in Python?

The Python string center() method is used to center a string value.

This is done by first setting a new length for the target string (A value beyond the current length of the string), then putting the string in the middle of the available space and finally filling those spaces that are left around with characters (the default is white space).

Python String center() Method Syntax:

string.center(length , character)

String center() Method Parameter

The center() method takes two arguments:

  • The firs argument is the new length for the target string value (note that the string itself won’t change but the result of this method will have the specified length).
  • The second argument is the character that we want to fill those spaces that left around after the target string was moved to center. The default value of this second argument is white space.

String center() Method Return Value

The return value of this method is a new string value that has the target string (the one that this method is invoked upon) set at the center and the white spaces around it is filled with the specified character (the second argument of the method).

Example: using string center() method in python

s1 = "THIS IS A STRING VALUE"

result = s1.center(100, "*")

print(result)

Output:

***************************************THIS IS A STRING VALUE***************************************
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies