String center()

Python String center() method returns a new string with the given string centered for a given length.

In this tutorial, we will learn the syntax and examples for center() method of String class.

Syntax

The syntax of String center() method in Python is

str.center(length, character)

where

ParameterRequired/OptionalDescription
lengthRequiredLength of the resulting string.
characterOptionalThe character with which the given string has to be padded with on both sides.
ADVERTISEMENT

Examples

Center a String

In this example, we will take a string 'abcd', and center the text with a resulting length of 10, using str.center() method.

Example.py

x = 'abcd'
length = 10
result = x.center(length)
print(f'Resulting string is : \'{result}\'')
Try Online

Output

Resulting string is : '   abcd   '

Uneven Padding

If the difference of resulting string length and given string length is not even, then the padded character on the left are more by one than that of the right.

Example.py

x = 'abcd'
length = 7
result = x.center(length)
print(f'Resulting string is : \'{result}\'')
Try Online

Output

Resulting string is : '  abcd '

center() with specific character

In the following program, we will specify the character with which the given string is appended with, on left and right of it.

Example.py

x = 'abcd'
length = 10
character = '-'
result = x.center(length, character)
print(f'Resulting string is : \'{result}\'')
Try Online

Output

Resulting string is : '---abcd---'

Conclusion

In this Python Tutorial, we learned how to center a string using String method – center().