learn python string center() with 3 example

The center() method in Python is used to center align the string. It takes two parameters:

1. width: Required. The width of the string to fill.

2. fillchar: Optional. The character to fill in the remaining space. If not provided, space is used as the fill character.

How to use the center() method:

# Without fillchar
text = "Hello, World!"
centered_text = text.center(20)
print(centered_text) # Outputs: '  Hello, World!  '

# With fillchar
centered_text_with_fillchar = text.center(20, '*')
print(centered_text_with_fillchar) # Outputs: '***Hello, World!***'

Example 1

Centering a string in a field of a certain width.

str1 = "AI"
centered_str1 = str1.center(10)
print(centered_str1) # Outputs: '  AI  '

Example 2

Centering a string with a custom fill character.

str1 = "Python"
centered_str1 = str1.center(20, '-')
print(centered_str1) # Outputs: '-------Python-------'

Example 3

When the width is less than the length of the string.

str1 = "Machine Learning"
centered_str1 = str1.center(10, '*')
print(centered_str1) # Outputs: 'Machine Learning'