Center() Function in Python
In Python, the center() function is employed to center text within a given string length. For instance, say we have a 6-letter word and want to center it within 8 spaces using the center() method, then there will be an empty space on either side of the word.
In this article, we will discuss the center() function and understand its use with the help of examples. We will be covering the following sections.
Table of Contents
- Introduction to center() Function in Python
- Examples of Using the center() Function in Python
- Errors that arise While Using center() in Python
What is center() Function in Python?
The center() method is a string method in Python that is used to align text within a given string length. It takes two arguments, the first being the desired width of the string, and the second being the character to be used for padding the string (default is whitespace).
When using the center() method, the text is placed in the center of the string, with padding characters added on both sides if necessary. If the desired width is less than the length of the text, the original text is returned unchanged.
Explore free Python courses
Best-suited Python courses for you
Learn Python with these high-rated online courses
Syntax of center()
The syntax of center() function in Python is given as:
string.center(width[, fillchar])
Parameters of center()
where:
- string is the string that you want to center
- width is the total width of the resulting string
- fillchar is the character that will be used to fill the remaining space (optional, default is whitespace)
Return Value of center()
The function returns a new string with added padding, either in the form of a space or a designated character.
One thing you need to keep in mind is that the center() method returns a newly updated string with the modified case, without altering the original string. Therefore, if you want to permanently modify the original string, you need to reassign the modified string back to the original variable.
Examples of Using Center() Function in Python
Example 1: Padding a String with Spaces
text = "Python"padded_text = text.center(10)print(padded_text)
Output:
Python
In this example, we are padding the string “Python” with spaces to center it within a string of length 10. The resulting string is assigned to the variable padded_text and printed to the screen.
Example 2: Padding a String with a Specified Character
text = "Challenger"padded_text = text.center(10, '*')print(padded_text)
Output:
Challenger**
In this example, we are padding the string “Challenger” with asterisks to center it within a string of length 10. The resulting string is assigned to the variable padded_text and printed to the screen.
Example 3: Padding a String with Uneven Widths
text = "Language"padded_text = text.center(11)print(padded_text)
Output:
Language
In this example, we are padding the string “Language” with spaces to center it within a string of length 11. Since 11 is an odd number, the padding will be uneven, resulting in an extra space on the left side of the string. The resulting string is assigned to the variable padded_text and printed to the screen.
Example 4: Handling Errors with try-except Block
text = 123try: padded_text = text.center(10)except TypeError: print("Error: The input value must be a string.")
Output:
Error: The input value must be a string.
In this example, we are attempting to pad the integer value 123 using the center() method, which will raise a TypeError. To handle this error, we use a try-except block to catch the exception and print an error message to the console.
Errors that arise While Using center() in Python
There are mainly two types of errors that can arise while using the center() method in Python:
Type Error
If the argument passed to the center() method is not a string, a TypeError will be raised. This can happen if the argument is an integer, float, list, tuple, or any other non-string type.
For example, the following code will raise a TypeError because the argument passed to the center() method is an integer, not a string:
number = 123padded_number = number.center(10)
Output:
TypeError: center() argument 1 must be str, not intpadded_number = number.center(10)
Value Error
If the width argument passed to the center() method is less than or equal to the length of the original string, no padding will be added, and the original string will be returned. If the width argument is negative, a ValueError will be raised.
For example, the following code will raise a ValueError because the width argument is negative:
word = "Hello"invalid_padding = word.center(-5)
Output:
ValueError: string center width must be >= 0
So, as we understood from the above examples, the center() method can raise a TypeError if the argument passed to it is not a string, and a ValueError if the width argument is negative.
Endnotes
Hope this article was helpful for you in understanding how and why the center() method is used in Python. If you wish to learn more about Python and practice Python programming, you can explore related articles here.
Explore programming courses
FAQs
What is the center() method used for in Python?
The center() method is used to center a string within a larger string, by adding padding characters to the left and right of the string.
What are the parameters of the center() method?
The center() method takes two parameters - the first is the width of the resulting string, and the second (optional) parameter is the padding character to be used. If the second parameter is not specified, the default padding character is a space.
How does the center() method handle odd-length strings?
If the original string has an odd length, the padding will be uneven, resulting in an extra space added to the left side of the string.
Can the center() method modify the original string?
No, the center() method does not modify the original string - it returns a new string with the added padding.
What kind of errors can arise while using the center() method?
The center() method can raise a TypeError if the argument passed to it is not a string, and a ValueError if the width argument is negative.
How can errors be handled while using the center() method?
Errors can be handled using a try-except block, which catches the exception raised by the center() method and allows the program to handle it gracefully
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio