lettura simple

The Python center Method

In Python, there's a super handy method called center() that allows you to neatly position a string right in the middle of a larger string. It does this by adding spaces (or any character of your choice) both before and after your original string.

string.center(length, fill_character)

This center() method works with String objects and takes two parameters:

  • Length. The total number of characters in the centered string. This one's a must-have.
  • Fill character. An optional parameter that lets you pick the character added before and after your string. If you don't specify it, the method will use empty spaces by default.

This method comes in handy when you want your text to look neat, tidy, and easily readable.

Let me walk you through an example.

First, create a string and store it in a variable called 'text'.

>>> text = "Hello world"

Next, make a new 20-character long string with "Hello world" nicely centered.

>>> text.center(20)

What you'll get is a larger 20-character string with "Hello world" sitting pretty in the middle.

Hello world

Since we didn't choose a fill character, the center() method just added spaces to the right and left to center our text.

The centered string is 20 characters long.

Keep in mind. Using text.center(20) won't change the content of the original "text" variable. It creates a brand new string instead. So, if you want to keep the new centered string, you can assign it to a new variable.

>>> centered_text = text.center(20)

Or, overwrite the content of the initial "text" variable:

>>> text = text.center(20)

Choosing a Fill Character

Want to get creative? The center method lets you specify a fill character other than the usual empty space.

For example, if you want to use the "-" character as your fill, type text.center(20,"-")

>>> text.center(20,"-")

Now, your output will look something like this:

----Hello world-----

The center method used the "-" character as our fill, making the string nicely centered.

il metodo center

And there you have it - the center method!




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin