Python String center Method - Python Tutorial | Logic Practice
Python Course / Data Types / Python String center Method

Python String center Method

BLUF: This lesson on Python String center Method provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python String center Method

Mastering Python String center Method is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The Python center function aligns a string centrally by adding padding on both the left and right sides of the string. This method accepts two arguments: the first is the desired width, while the second, which is optional, is the fillchar. The fillchar defines the character that will be employed to fill the padding on either side of the string.

Python String center Method

It has the following syntax:

Example

center(width[,fillchar])

Parameters

  • width (required)
  • fillchar (optional)
  • Return Type

It returns modified string.

Different Examples for Python String center Method

In this section, we will explore multiple examples to illustrate the usage of the string center method in Python.

Python String Center Method Example 1: default fill char

In this instance, we did not provide a second argument. By default, it assumes spaces.

Example

# Python center() function example

# Variable declaration

str = "Hello World"

# Calling function

str2 = str.center(20)

# Displaying result

print("Old value:", str)

print("New value:", str2)

Output:

Output

Old value: Hello World

New value:   Hello World

Python String Center Method Example 2

In this instance, we are supplying the padding character (which is optional) as #. Refer to the example provided.

Example

# Python center() function example

# Variable declaration

str = "Hello World"

# Calling function

str2 = str.center(20,'#')

# Displaying result

print("Old value:", str)

print("New value:", str2)

Output:

Output

Old value: Hello World

New value: ##Hello World##

Python String Center Method Example 3

Let us consider an additional example to illustrate the usage of the string center method in Python.

Example

# Python center() function example

# Variable declaration

str = "Hello World"

if str == "Hell0 ExampleTech":

    str2 = str.center(20,'#')

else:

    str2 = str.center(20,'!')

# Displaying result

print("Old value:", str)

print("New value:", str2)

Output:

Output

Old value: Hello World

New value: !!Hello World!!

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience