The Wayback Machine - https://web.archive.org/web/20220311134412/https://www.geeksforgeeks.org/python-string-center-method/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python String center() Method

  • Difficulty Level : Easy
  • Last Updated : 05 Aug, 2021

Python String center() method creates and returns a new string that is padded with the specified character. 

Syntax: 

string.center(length[, fillchar])

Parameters:

  • length: length of the string after padding with the characters.
  • fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument.

Returns:

Returns a string padded with specified fillchar and it doesn’t modify the original string.

Example 1: center() Method With Default fillchar

Python




# Python program to illustrate
# string center() in python
string = "geeks for geeks"
  
new_string = string.center(24)
  
# here filchar not provided so takes space by default.
print "After padding String is: ", new_string

Output: 

After padding String is:      geeks for geeks

Example 2: center() Method With # fillchar 

Python




# Python program to illustrate
# string center() in python
string = "geeks for geeks"
  
new_string = string.center(24, '#')
  
# here fillchar is provided
print "After padding String is:", new_string

Output: 

After padding String is: ####geeks for geeks#####
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!