How to centered string in Python

Posted on
How to Returns a centered string in Python

Python Tutorial

One of the capabilities of Python is to put or returns a centered string in a character set.

To make it easier to understand, look at the following example:

x = "nice"
y = "--------------------"

We want the “nice” string to be right in the middle of the “——————–” character set. So it becomes like this:


Automatically, python will read the number of characters that we specify and put the string right in the center of the character set.

The method we use is center()

The basic syntax is:, character)

First example:

I have string in variable x. In variable of y I have char “-“.

Using center() method, i will generate automaticly the char “-” as much as 20.

Then I want to centered the string “nice” in char set.

x = "nice"
y = "-"
z =, y)


The result is:


Second Example

You can change the program line above as follows and run with the same result.

x = "nice"
z =, "-")


The result is:


Third example

If you don’t want to show characters and just put the string in the middle of the specified number of characters, then the program as follows:

x = "nice"
z =


Then the result character will be replaced with a space so you see the result as follows:


Hopefully this Returns a centered string Python article is useful for you.



Leave a Reply

Your email address will not be published. Required fields are marked *