Python String center() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

The center() method in Python will align the string to the center, using a specified character(by default, it is space) as the fill character.

Syntax of center() method

string.center(length, character)

length - The length of the required string(Required)
character - The fill character for the missing space(Optional).
            By default is space.
Example 1

Code

str1 = "Pylenin"

str2 = str1.center(10)

print(str2)

print(f"Str1 length was {len(str1)}")
print(f"Str2 length is {len(str2)}")

Output

 Pylenin  
Str1 length was 7
Str2 length is 10

The length of the new string has become 10. The increase in length was due to addition of space characters to the original string.

Example 2

Code

str1 = "Pylenin"

str2 = str1.center(10, '*')

print(str2)

print(f"Str1 length was {len(str1)}")
print(f"Str2 length is {len(str2)}")

Output

*Pylenin**
Str1 length was 7
Str2 length is 10

By providing the optional character parameter, you can see how the new string has changed.

Example 3 - Printing Pyramid Patterns in Python

You can do many exciting things with center() method in Python. For example - Constructing a Pyramid.

Code

for i in range(1, 10, 2):
    x = i*'*'
    print(x.center(10))

Output

    *     
   ***    
  *****   
 *******  
********* 

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide