Python string center method explanation with example

Published by admin on

Python string center method explanation with example

Introduction :

center() is an inbuilt method defined in the python string. Using this method, we can centre align a string. By default, we can centre align a string with space on its side. Or we can give specific characters as the fill character.

 

Syntax of center() :

Following is the syntax of center() :

str.center(length,fillchar)

Here,str is the string, length is the total length of the final string and fillchar is the character to fill both side of the string str.

fillchar is optional. If you don’t pass any character as fillchar, it will use blank space to fill on both sides of the string.

 

Return value of center() :

This method returns one string with the caller string str in the middle and fillchar on the sides.

 

Python program :

Let’s try to implement center() method :

original_str = "hello world"

print(original_str.center(10))

print(original_str.center(30))

print(original_str.center(30,'*'))

It will give the below output :

hello world
         hello world
*********hello world**********

 

Explanation :

  • For the first print statement, the result string doesn’t have any change because we want to center 10 characters of the string, but the size of the string is 11.
  • The second string size is 30 total with equal amount of blank spaces on both side.
  • The third string size is 30 total with * on both side.

python center method

Categories: python

0 Comments

Leave a Reply

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