Open In App
Related Articles

Python String center() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 String center() Method tries to keep the new string length equal to the given length value and fills the extra characters using the default character (space in this case).

Python3

string = "geeks for geeks"
 
new_string = string.center(24)
 
# here fillchar 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 ‘#’ as fillchar

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

Example 3: center() Method with length argument value less than original String length

Python3

string = "GeeksForGeeks"
# new string will be unchanged
print(string.center(5))

                    

Output:

GeeksForGeeks

Explanation: Here, in the output, the new string is unchanged, because the original string length (13) is more than the length value provided (5). Thus, the new string returned is unchanged.



Last Updated : 17 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads