
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:
--------nice--------
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:
string.center(length, 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 = x.center(20, y)
print(z);
The result is:
--------nice--------
Second Example
You can change the program line above as follows and run with the same result.
x = "nice"
z = x.center(20, "-")
print(z);
The result is:
--------nice--------
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 = x.center(20)
print(z);
Then the result character will be replaced with a space so you see the result as follows:
nice
Hopefully this Returns a centered string Python article is useful for you.
READ NEXT