Python 3 – String center() Method
When working with strings in Python, there are many methods available to manipulate and format them in different ways. One such method is the center()
method, which can be used to center a string within a given width. In this article, we will go over the center()
method in detail, including how it works and some examples of how to use it.
The center()
method
The center()
method is used to center a string within a given width. It takes one required argument, which is the width of the resulting string. This width includes any characters in the original string, so the resulting string may be longer than the original if the width is too narrow.
The syntax for the center()
method is as follows:
string.center(width[, fillchar])
Here, string
is the original string that we want to center, width
is the total width of the resulting string, and fillchar
is an optional argument that specifies the character to use for filling any extra space in the resulting string. By default, the fillchar
value is a space.
Examples
Let’s take a look at some examples of how to use the center()
method in Python. In each example, we will use a different value for the width
parameter to show how the resulting string changes.
Example 1: Basic usage
text = "Hello, world!"
print(text.center(20))
Output:
Hello, world!
In this example, we use the center()
method to center the string "Hello, world!"
within a width of 20
. Since the length of the original string is 13
, the resulting string is 20
characters long and has 7
spaces on either side of the original string.
Example 2: Custom fill character
text = "Hello, world!"
print(text.center(20, '-'))
Output:
--Hello, world!---
In this example, we specify a custom fill character of -
by passing it as the second argument to the center()
method. As a result, the resulting string has -
characters on either side of the original string instead of spaces.
Example 3: Narrow width
text = "Hello, world!"
print(text.center(10))
Output:
Hello, world!
In this example, we use a width of 10
, which is smaller than the length of the original string. Since the width is too narrow to center the string, the resulting string is just the original string without any extra characters added.
Conclusion
The center()
method is a useful tool for formatting strings in Python. It allows you to easily center a string within a given width, and even allows you to use custom fill characters if you need to. By using the center()
method, you can create cleaner and more readable code that is easier to understand and maintain.