Thursday, November 28, 2024
Google search engine
HomeLanguagesPython String center() Method

Python String center() Method

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 = "Lazyroar for Lazyroar"
 
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:      Lazyroar for Lazyroar     

Example 2: center() Method With ‘#’ as fillchar

Python




string = "Lazyroar for Lazyroar"
 
new_string = string.center(24, '#')
 
# here fillchar is provided
print("After padding String is:", new_string)


Output: 

After padding String is: ####Lazyroar for Lazyroar#####

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.

RELATED ARTICLES

Most Popular

Recent Comments